<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Oversea extends CI_Controller {

	/**
	 * 海外运输管理
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	function __construct()
	 {
		parent::__construct();
		$this->load->model('Function_m','fun');
		$this->load->model('Oversea_m','m');
		$this->load->model('User_m','u');
		$this->pageSize =$this->config->item('pagenum');
	 }


	public function product()
	{
		
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;
		
		$status =  $this->input->get('status');
		if($status){
			$where =" AND status ='".$status."'";
			$this->tpl->assign("status",$status);
		}
		else
		$where =" AND status !=4 AND status !=3";
		$starttime = trim($_POST["starttime"]);
		if($starttime)
		{
			$where.=" AND opertime >='".$starttime."'";
			$this->tpl->assign("starttime",$starttime);
		}
		$endtime =trim($this->input->get('endtime'));
		if($endtime)
		{
			$where.=" AND opertime <='".$endtime."'";
			$this->tpl->assign("endtime",$endtime);
		}
		$other = trim($this->input->get('other'));
		if($other)
		{
			$where.=" AND (name like '%".$other."%' or sku like '%".$other."%')";
			$this->tpl->assign("other",$other);
		}

		$st = $this->input->get('st');
		if($st)
		{
			if($st ==1)
			{
				$where.=" AND (st =1)";
			}
			if($st ==2)
			{
				$where.=" AND (hw =1)";
			}
			
			$this->tpl->assign("st",$st);
		}

		$id =  $this->input->get('id');
		if($id)
		{
			$where.=" AND id='".$id."'";
		}
		$orderyts =  $this->input->get('ordery');
		if($orderyts)
		{
			$orderby =" order by id {$orderyts}";
			if($orderyts=='ASC')
			{
				$this->tpl->assign("orderyts",'DESC');
			}else{
				$this->tpl->assign("orderyts",'ASC');
			}

		}else{
			$this->tpl->assign("orderyts",'ASC');
		}
		$orderbysku =  $this->input->get('orderbysku');
		if($orderbysku)
		{
			$orderby =" order by sku {$orderbysku}";
			if($orderbysku=='ASC')
			{
				$this->tpl->assign("orderbysku",'DESC');
			}else{
				$this->tpl->assign("orderbysku",'ASC');
			}

		}else{
			$this->tpl->assign("orderbysku",'DESC');
		}
		if(!$orderbysku && !$orderyts)
		{
			$orderby =" order by sku ASC";
		}

		if($_COOKIE['ext_userid'])
		{
			$ext_userID = $_COOKIE['ext_userid'];
			$where.=$where." AND oper in ($ext_userID)";
		
		}else{
			if($_COOKIE["department"] != 1){
				$notext_userID = $_COOKIE['notext_userid'];
				if($notext_userID){
					$where.=$where." AND oper not in ($notext_userID)";
				}
			}
		}

		$list = $this->fun->getalllist('`t_overseaproduct`',$where,$nowpage,$if_csv,$this->pageSize,$orderby);
		foreach($list["list"] as $key=>$rs)
		{
			if($rs["status"] ==1)$list["list"][$key]["status"] ="正常";
			if($rs["status"] ==2)$list["list"][$key]["status"] ="清仓";
			if($rs["status"] ==3)$list["list"][$key]["status"] ="停产";
			if($rs["status"] ==4)$list["list"][$key]["status"] ="自建";
		}
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("department", $_COOKIE["department"]);
		$this->tpl->assign("list",$list["list"]);
		$this -> tpl -> display("oversea/product.tpl");
	}
	public function stocklist()
	{
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;
		
		
		$where = " AND stock >0";
		$other = $this->input->get_post('other');
		if($other)
		{
			$where.=" AND (sku like '%".$other."%' )";
			$this->tpl->assign("other",$other);
		}
		
		$list = $this->fun->getalllist('t_overseastock',$where,$nowpage,$if_csv,$this->pageSize);
		foreach($list["list"] as $key=>$rs)
		{
			$where = " AND sku = '".$rs["sku"]."'";
			$detail = $this->fun->getdatabasesdetail('t_overseaproduct',$where);
			$list["list"][$key]["goods"] = $detail;
			
		}
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		$this -> tpl -> display("oversea/stocklist.tpl");
	}
	public function purchasing()
	{

		if($_COOKIE["classid"]==14)
		{

			if($_COOKIE["shopname"])
			{
				$shopname = unserialize($_COOKIE["shopname"]);
				$shopname = implode("','",$shopname);
				$this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop',"  AND name in('".$shopname."') AND openflag= 1",'id,name',' order by name asc'));//查所有店铺
			}else{
				$this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop',"  AND openflag= 1",'id,name',' order by name asc'));//查所有店铺
			}
		
			$this->tpl->assign("overseawarehouse", $this->fun->getdatabaseslist('t_overseawarehouse',"AND yz=0 ",'id,name',' order by paixu asc'));
			
		}else{
			$this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop','AND openflag= 1','id,name',' order by name asc'));//查所有店铺
			//查所有仓库
			$this->tpl->assign("overseawarehouse", $this->fun->getdatabaseslist('t_overseawarehouse',' AND yz=0','id,name',' order by paixu asc')); 
		}
		
			if($this->config->item('transportmodelist')){
			 $transportmodelist = explode("|",$this->config->item('transportmodelist'));
			 $this->tpl->assign("transportmodelist",$transportmodelist);
			}

		$this -> tpl -> display("oversea/purchasing.tpl");
	}
	public function savepurchasing()
	{
		$this->m->savepurchasing();
		header("location:/oversea/purchasinglist");
	}
	public function purchasinglist()
	{
		$nowpage = $_REQUEST["pageid"];

		
        $shiptype=$this->input->get("shiptype");
        $createUser=trim($this->input->get("createUser"));
 	    if ($nowpage == "")
            $nowpage = 1;
		
		if($this->config->item('ispurchasinglist')==1)
		{
			if($_COOKIE["department"]==1 || $_COOKIE["department"]==2)	//主管和经理能看到所有的销售
			{
			
			}else{
				//$where = " AND create_id='".$_COOKIE["userid"]."'";
			}
		}else{
			//$where = " AND create_id='".$_COOKIE["userid"]."'";
		}
		
        if($createUser)
		{
			$where.=" AND (create_user like '%".$createUser."%' )";
			$this->tpl->assign("createUser",$createUser);
		}
		if(count($_GET)==0)
		{
			$where.=" AND status in(0,1,2,3)";
		}
		if($shiptype)
		{
			if($shiptype==11)
			{
				$nty = 0;
			}else{
				$nty = $shiptype;
			}
        	$where.=" AND status ='".$nty."'";
			$this->tpl->assign("shiptype",$shiptype);
		}
		$starttime = trim($_GET["starttime"]);
		if($starttime)
		{
			$where.=" AND updatetime >='".$starttime."'";
			$this->tpl->assign("starttime",$starttime);
		}
		$endtime =trim($this->input->get('endtime'));
		if($endtime)
		{
			$where.=" AND updatetime <='".$endtime."'";
			$this->tpl->assign("endtime",$endtime);
		}
		$other = trim($this->input->get('other'));
		if($other)
		{
			$where.=" AND (demand_number like '%".$other."%' )";
			$this->tpl->assign("other",$other);
		}
		$shopname = trim($this->input->get('shopname'));
		if($shopname)
		{
			$where.=" AND (shopname like '%".$shopname."%' )";
			$this->tpl->assign("shopname",$shopname);
		}

		$sku = trim($this->input->get('sku'));
		if($sku)
		{
			$where.=" AND id in (select demandID from t_overseapurchasing where goodsno like '%".$sku."%')";
			$this->tpl->assign("sku",$sku);
		}
		$orderby =" order by id DESC";
		$list = $this->fun->getalllist('t_oversea_demand',$where,$nowpage,$if_csv,$this->pageSize,$orderby);
		foreach($list["list"] as $key=>$rs)
		{
			$goodslist = $this->fun->getdatabasesdetail("t_overseapurchasing","  AND demandID = '".$rs["id"]."'","GROUP_CONCAT(goodsno) as goodsno");
			$list["list"][$key]["goodssku"] = implode("<br>",explode(",",$goodslist["goodsno"]));

			if($_COOKIE["userid"] == $rs["create_id"])
			{
				$list["list"][$key]["isedit"] = 1;
			}else{
				$list["list"][$key]["isedit"] = 0;
			}
		}
		
		/*
        $stock_where=' and storage_id in(1,2)';
        if(count($goods_skus)>0){
            $goods_sku_str=implode("','",$goods_skus);
            $stock_where.=" and goods_sku in('$goods_sku_str')";
        }
		$have_stocks=$this->fun->getdatabaseslist("db_goods left join db_goods_stock B on db_goods.goods_id=B.goods_id","$stock_where",
        "db_goods.goods_sku,B.goods_id,sum(B.stock) as allstock,sum(B.in_transit) as all_in_transit,B.waitday"," group by B.goods_id");

        $goods_stocks=iarray_column($have_stocks,'allstock','goods_sku');
        $in_transits=iarray_column($have_stocks,'all_in_transit','goods_sku');
        $waitdays=iarray_column($have_stocks,'waitday','goods_sku');
        foreach($list["list"] as $key=>$rs){
			$list["list"][$key]["goods_stock"] = $goods_stocks[$rs['sku']];
            $list["list"][$key]["in_transit"] = $in_transits[$rs['sku']];
            $list["list"][$key]["waittime_limit"] = $waitdays[$rs['sku']];
            $list["list"][$key]["waitdays"] = date("Y-m-d",$waitdays[$rs['sku']]);
        }*/
		
		//一审人员和二审人员
		$firsttrial = $this->config->item('firsttrial');//一审人员
		if($firsttrial){
			$firsttrial = explode("|",$firsttrial);
			foreach($firsttrial as $rs)
			{
				if(trim($_COOKIE["username"]) == trim($rs))
				{
					$this->tpl->assign("firsttrialman",1);
				}
			}
		}else{
			$this->tpl->assign("firsttrialman",0);
		}

		$secondtrial = $this->config->item('secondtrial');//二审人员

		if($secondtrial){
			$secondtrial = explode("|",$secondtrial);

			foreach($secondtrial as $rs)
			{
				if($_COOKIE["username"] == $rs)
				{
					$this->tpl->assign("secondtrialman",1);
				}
			}
		}else{
			 $this->tpl->assign("secondtrialman",$_COOKIE["department"]);
		}
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		$this -> tpl -> display("oversea/purchasinglist.tpl");
		
	}
	
	/******************************************
	**  二审通过之后的需求进行仓库库存预报
	***************************************************/
	public function deliveryplanpro()
	{
		$this->m->saveoverseapurchasingstatus();
		$nowpage = $_REQUEST["pageid"];
        $shiptype=$this->input->get("shiptype");
        $createUser=trim($this->input->get("createUser"));
 	    if ($nowpage == "")
            $nowpage = 1;
		

		if($this->config->item('ispurchasinglist')==1)
		{
			if($_COOKIE["department"]==1 || $_COOKIE["department"]==2 || $_COOKIE["classid"]==10  || $_COOKIE["classid"]==4 || $_COOKIE["userid"]==294|| $_COOKIE["userid"]==327)	//主管和经理,仓库能看到所有的销售
			{
				if($_COOKIE["classid"]==4)	//日本销售部
				{
					$where = " AND create_id in (SELECT DISTINCT id  FROM `d_user` WHERE (classid = 4  or id = 303) AND type=1)";
				}
				if($_COOKIE["classid"]==10) //欧美
				{
					$where = " AND create_id not in (SELECT DISTINCT id  FROM `d_user` WHERE classid = 4 AND type=1) AND starthouse in ('1号仓库 (C1)','2号仓库 (C2)','3号仓库 (C3)')";
				}
				if($_COOKIE["userid"]==294 || $_COOKIE["userid"]==327)
				{
					$where = " AND create_id not in (SELECT DISTINCT id  FROM `d_user` WHERE classid = 4 AND type=1) AND starthouse in ('英华英国仓 (E2)','英华德国仓 (D2)','EZGO美国仓 (U2)','万邑通美西仓 (USWC)','Amazon FBA')";
				}
				/*
				if($_COOKIE["userid"]==327)
				{
					$where = " AND create_id not in (SELECT DISTINCT id  FROM `d_user` WHERE classid = 4 AND type=1) AND starthouse in ('EZGO美国仓 (U2)','万邑通美西仓 (USWC)')";
				}*/
				
					
				
			
			}else{
				$where = " AND create_id='".$_COOKIE["userid"]."'";
			}
		}else{
			$where = " AND create_id='".$_COOKIE["userid"]."'";
		}
		
		/**如果进来的是开发人员，还需要看到与自己有关的SKU**/
		
		 //获取外采购商品开发人员对应的仓库
        $str_warehouse = $this->config->item('temporary_warehouse');
        $arr_warehouse = explode("\n",$str_warehouse);
        $arr_persons = array(); //维护人员
        foreach($arr_warehouse as $k=>$v){
            $arr_value = explode("|",trim($v));
            $arr_persons[$k] = $arr_value[0];
        }
		
	    if(in_array($_COOKIE["username"],$arr_persons)){
		  $formts= " left JOIN db_goods C on A.goodsno = C.goods_sku ";
		  $where=" AND C.g_buyer = '".$_COOKIE["username"]."'";
		}
		
		
        if($createUser)
		{
			$where.=" AND (create_user like '%".$createUser."%' )";
			$this->tpl->assign("createUser",$createUser);
		}
		$verify = $this->input->get('verify');
		 if($verify)
		{
			if($verify==2)
			{
				$where.=" AND (verify_tip =1 AND verifyNums = 0 )";
			}
			if($verify==1)
			{
				$where.=" AND (verify_tip =1 AND verifyNums > 0 )";
			}
			
			$this->tpl->assign("verify",$verify);
		}
		if($shiptype)
		{
			if($shiptype==11)
			{
				$nty = 0;
			}else{
				$nty = $shiptype;
			}
        	$where.=" AND status ='".$nty."'";
			$this->tpl->assign("shiptype",$shiptype);
		}
		$starttime = trim($_GET["starttime"]);
		if($starttime)
		{
			$where.=" AND updatetime >='".$starttime."'";
			$this->tpl->assign("starttime",$starttime);
		}
		$endtime =trim($this->input->get('endtime'));
		if($endtime)
		{
			$where.=" AND updatetime <='".$endtime."'";
			$this->tpl->assign("endtime",$endtime);
		}
		$other = trim($this->input->get('other'));
		if($other)
		{
			$where.=" AND (demand_number like '%".$other."%' )";
			$this->tpl->assign("other",$other);
		}
		$shme = trim($this->input->get('shopname'));
		if($shme)
		{
			$where.=" AND ( A.shopname like '%".$shme."%' )";
			$this->tpl->assign("shopnameselect",$shme);
		}

		$sku = trim($this->input->get('sku'));
		if($sku)
		{
			$where.=" AND  goodsno like '%".$sku."%'";
			$this->tpl->assign("sku",$sku);
		}
		if($_COOKIE["classid"]==10)
		{
			$orderby = " order by goodsno DESC";
		}else{
			$orderby = " order by demandID ASC";
		}

		$where.=" AND A.demandID >0 and B.status =3 AND A.status=0";
		$field = " A.* ,B.demand_number,B.create_user,B.updatetime,B.starthouse,B.transportation";
		$list = $this->fun->getalllist("t_overseapurchasing A left join t_oversea_demand B on A.demandID = B.id $formts",$where,$nowpage,$if_csv,$this->pageSize,$orderby,$field);
		//echo $this->db->last_query();
		foreach($list["list"] as $key=>$rs)
		{
			$goodsInfo = $this->fun->getdatabasesdetail("db_goods"," and goods_sku='".$rs["goodsno"]."'");
			$goodsstock = $this->fun->getdatabasesdetail("db_goods_stock","  AND storage_id in (1,2) and goods_id='".$goodsInfo["goods_id"]."'","sum(stock) as stock");
			
			$list["list"][$key]["goods_name"] = $goodsInfo["goods_name"];
			$list["list"][$key]["stock"] = $goodsstock["stock"];
			$list["list"][$key]["sales1"] = $goodsInfo["sales1"];
			$list["list"][$key]["sales2"] = $goodsInfo["sales2"];

			$goodsstock_transit = $this->fun->getdatabasesdetail("db_goods_stock"," and goods_id='".$goodsInfo["goods_id"]."' and in_transit >0");
			$list["list"][$key]["in_transit"] = $goodsstock_transit["in_transit"]?$goodsstock_transit["in_transit"]:0;
			if($goodsstock_transit["in_transit"]>0 && $goodsstock_transit["waitday"])
			{
				$list["list"][$key]["waitday"] = date("Y-m-d",$goodsstock_transit["waitday"]);
			}
			$list["list"][$key]["statsbyNum"] = $rs["skunum"] - $rs["sendnums"]; 
			//FBA待发货数
			$Needgoodsstock = $this->fun->getdatabasesdetail("t_overseapurchasing"," AND demandID in(SELECT DISTINCT id  FROM `t_oversea_demand` WHERE status = 3) and status = 0 and goodsno='".$rs["goodsno"]."'","SUM(skunum) AS needskunum ,SUM(sendnums) AS needsendnums");
			$needskunum = $Needgoodsstock["needskunum"] - $Needgoodsstock["needsendnums"];
			$list["list"][$key]["Needgoodsstock"] = $needskunum?$needskunum:0;

			//直发待发货
			$sql = "SELECT sum(goods_number) as goods_number FROM db_order_sell A left join db_order_list B on A.`order_id` = B.order_id where A.`goods_id` = '".$goodsInfo["goods_id"]."' AND B.order_status in (2,3) and B.shipping_status = 5 AND B.is_nodelivery = 0 ";
			$res = $this->db->get_one($sql);
			$list["list"][$key]["sendgoodsnum"] = $res["goods_number"]?$res["goods_number"]:0;
			

			$goodsInfoover = $this->fun->getdatabasesdetail("t_overseaproduct"," and sku='".$rs["goodsno"]."'","st,hw");
			$list["list"][$key]["st"] = $goodsInfoover["st"];
			$list["list"][$key]["hw"] = $goodsInfoover["hw"];
			
			//海外仓库存
			$storage_ids = 0;
			if($rs["starthouse"] =='英华英国仓 (E2)')	//减英国仓库存
			{
				$storage_ids = 3; 
			}
			if($rs["starthouse"] =='英华德国仓 (D2)')	
			{
				$storage_ids = 5; 
			}
			if($rs["starthouse"] =='万邑通美西仓 (USWC)')	
			{
				$storage_ids = 7; 
			}
			if($rs["starthouse"] =='EZGO美国仓 (U2)')
			{
				$storage_ids = 6; 
			}
			if($storage_ids>0)
			{
				$goodsseastock = $this->fun->getdatabasesdetail("db_goods_stock","  AND storage_id=$storage_ids and goods_id='".$goodsInfo["goods_id"]."'","sum(stock) as stock");
			}
			$list["list"][$key]["goodsseastock"] = $goodsseastock["stock"]?$goodsseastock["stock"]:0;

		}
		
	
		//一审人员和二审人员
		$firsttrial = $this->config->item('firsttrial');//一审人员
		if($firsttrial){
			$firsttrial = explode("|",$firsttrial);
			foreach($firsttrial as $rs)
			{
				if(trim($_COOKIE["username"]) == trim($rs))
				{
					$this->tpl->assign("firsttrialman",1);
				}
			}
		}else{
			$this->tpl->assign("firsttrialman",0);
		}

		$secondtrial = $this->config->item('secondtrial');//二审人员

		if($secondtrial){
			$secondtrial = explode("|",$secondtrial);

			foreach($secondtrial as $rs)
			{
				if($_COOKIE["username"] == $rs)
				{
					$this->tpl->assign("secondtrialman",1);
				}
			}
		}else{
			 $this->tpl->assign("secondtrialman",$_COOKIE["department"]);
		}
		
		

		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("classid", $_COOKIE["classid"]);
		$this->tpl->assign("userid", $_COOKIE["userid"]);
		$this->tpl->assign("shopname", $this->fun->getdatabaseslist("t_overseapurchasing"," AND status =0 and shopname !=''"," DISTINCT shopname "));
		$this->tpl->assign("list",$list["list"]);
		//获取自己所有的TA
		if($_COOKIE["userid"])
		{
			$this->tpl->assign("Talist", $this->fun->getdatabaseslist("t_oversea_demand"," AND status=3 AND create_id='".$_COOKIE["userid"]."'"," demand_number,id "));
		}
		if($_COOKIE["department"]==1)
		{
			$this->tpl->assign("Talist", $this->fun->getdatabaseslist("t_oversea_demand"," AND status=3 "," demand_number,id "));
		}
		$this -> tpl -> display("oversea/deliveryplanpro.tpl");
	}
	public function deliveryplan()
	{
	
		$ppid = $this->input->post('ppid');
		if($ppid=="")
		{
			die("Error");
		}
		
		
		if($ppid)
		{
			$list= "";
			$shipNums = $this->input->post('shipNums');
			$verifyNums= $this->input->post('verifyNums');
			foreach($ppid as $key=>$rs)
			{
				
				if($shipNums[$rs][0]==0)
				{
					continue;
				}


				$reslist = $this->fun->getdatabasesdetail("t_overseapurchasing A left join t_oversea_demand B on A.demandID = B.id"," AND A.id ='".$rs."'","A.* ,B.demand_number,B.create_user,B.updatetime,B.starthouse,B.transportation ");
				$goodsInfo = $this->fun->getdatabasesdetail("db_goods"," and goods_sku='".$reslist["goodsno"]."'");
				//获取FNSKU

				if($shipNums[$rs][0]>$verifyNums[$rs][0])
				{
					echo $reslist["goodsno"]."没那么多可发货数！";
					die;
				}

				$shopnameselect = $reslist["shopname"];
				
				if($shopnameselect){
					$fnsku = $this->fun->getdatabasesdetail("t_overseapurchasing"," and goodsno='".$reslist["goodsno"]."' AND shopname ='".$shopnameselect."' AND fnsku !='' ",'fnsku');
					$reslist["fnsku"] = $fnsku["fnsku"];
				}
				
				$reslist["shipNums"] =  $shipNums[$rs][0];
				$reslist["goods_name"] = $goodsInfo["goods_name"];
				$list[] = $reslist;
			}
			if(count($list)>0)
			{
				$demandID = $list[0]["demandID"];
				$seawarehouseselect = $list[0]["seawarehouse"];
				$shopnameselect = $list[0]["shopname"];
				$starthouseselect = $list[0]["starthouse"];
				$transportationselect = $list[0]["transportation"];
				$this->tpl->assign("starthouseselect",$starthouseselect);
				$this->tpl->assign("seawarehouseselect",$seawarehouseselect);
				$this->tpl->assign("shopnameselect",$shopnameselect);
				$this->tpl->assign("transportationselect",$transportationselect);
			}
			
			$list = $this->fun->multi_array_sort($list,"goodsno");	
			$this->tpl->assign("list",$list);

		}

		if($_COOKIE["classid"]==14)
		{

			if($_COOKIE["shopname"])
			{
				$shopname = unserialize($_COOKIE["shopname"]);
				$shopname = implode("','",$shopname);
				$this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop',"  AND name in('".$shopname."') AND openflag= 1",'id,name',' order by name asc'));//查所有店铺
			}else{
				$this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop',"  AND openflag= 1",'id,name',' order by name asc'));//查所有店铺
			}
			//查所有仓库
			$this->tpl->assign("overseawarehouse", $this->fun->getdatabaseslist('t_overseawarehouse',"AND yz=0 ",'id,name',' order by paixu asc'));
			
		}else{
			$this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop','AND openflag= 1','id,name',' order by name asc'));			//查所有店铺
			//查所有仓库
			$this->tpl->assign("overseawarehouse", $this->fun->getdatabaseslist('t_overseawarehouse',' AND yz=0','id,name',' order by paixu asc'));
			
		}




		if($this->config->item('transportmodelist')){
			 $transportmodelist = explode("|",$this->config->item('transportmodelist'));
			 $this->tpl->assign("transportmodelist",$transportmodelist);
			}
		

		if($this->config->item('carrierlist')){
		 $carrierlist = explode("|",$this->config->item('carrierlist'));
		 $this->tpl->assign("carrierlist",$carrierlist);
		}
		
		$this -> tpl -> display("oversea/deliveryplan.tpl");
	}
	/********
	**
	**	生成发货计划
	*/
	public function savepacking()
	{	
		
		if( $this->input->post('competenceID')=="")
		{
			show_error("请选择需要发货的商品！");
		}
		$this->tpl->assign("shopname",$this->input->post('shopname'));
		$this->tpl->assign("carrier",$this->input->post('carrier'));
		$this->tpl->assign("transportmode",$this->input->post('transportmode'));
		$this->tpl->assign("starthouse",$this->input->post('starthouse'));
		$this->tpl->assign("endhouse",$this->input->post('endhouse'));
		$this->tpl->assign("carrier",$this->input->post('carrier'));
		
		if(strstr($this->input->post('endhouse'),"Amazon"))
		{
			$this->tpl->assign("showfile",1);
		}else{
			$this->tpl->assign("showfile",0);
		}

		
		$upfiles = $_FILES["upfiles"];
		$this->tpl->assign("upfiles",$upfiles);
		$list = $this->m->getpacking();
		foreach($list["goodslist"] as $key=>$rs)
		{
			$totalnum =$totalnum+$rs["sendnums"];
			$totalprice =$totalprice+$rs["totalprice"];
		}
		
		$goodslist = $list["goodslist"];
		$detail = $list["detail"];
		
	
		$this->tpl->assign("totalsku",count($goodslist));	//所有要发的商品总数
		$this->tpl->assign("totalnum",$totalnum);	//所有要发的商品总数
		$this->tpl->assign("totalprice",$totalprice);	//所有要发的商品总金额
		$this->tpl->assign("goodslist",$goodslist);	//所有要发的商品列表
		$this->tpl->assign("detail",$detail);//所有要发的商品的详细列表
		$this->tpl->assign("hiddengoodslist",serialize($goodslist));	//所有要发的商品列表
		$this->tpl->assign("hiddendetail",serialize($detail));//所有要发的商品的详细列表

		$this->tpl->assign("configoverseadetail",$this->config->item('overseadetail'));//显示明细
		
		if($this->config->item('carrierlist')){
		 $carrierlist = explode("|",$this->config->item('carrierlist'));
		 $this->tpl->assign("carrierlist",$carrierlist);
		}
		
		$this -> tpl -> display("oversea/packingshow.tpl");
	
	}

	public function savedelivery()
	{
	
		$id = $this->m->savedelivery();
		header("location:/oversea/deliveryplanlist?id={$id}");
	}
	public function deliveryplanlist()
	{
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;
		
		if( $_COOKIE["department"]==10)
		{
			$where = " AND status !=7";
		}else{
			//$where = " AND createoper='".$_COOKIE["username"]."'";
		}
		if($_COOKIE['ext_userid'])
		{
			$ext_userID = $_COOKIE['ext_userid'];
			$rsUser = $this->db->get_one("SELECT GROUP_CONCAT(name) as username from d_user where id in($ext_userID) ");
			if($rsUser["username"])
			{
				$Uname = explode(",",$rsUser["username"]);
				$uName = implode("','",$Uname);
			}
			$where.=" AND createoper in ('$uName')";
		
		}else{
//			if($_COOKIE["department"] != 1){
//				$notext_userID = $_COOKIE['notext_userid'];
//				if($notext_userID){
//					//$where.=$where." AND p_createID not in ($notext_userID)";
//				}
//			}
		}

		
		//$where.=" AND status!=5";
		$starttime = trim($this->input->get('starttime'));
		if($starttime)
		{
			$where.=" AND createtime >='".$starttime."'";
			$this->tpl->assign("starttime",$starttime);
		}
		$endtime =trim($this->input->get('endtime'));
		if($endtime)
		{
			$where.=" AND createtime <='".$endtime."'";
			$this->tpl->assign("endtime",$endtime);
		}

		$st =trim($this->input->get('st'));
		if($st)
		{
			$this->tpl->assign("st",$st);
		}
		if($st == 1){
			$other = trim($this->input->get('other'));
			if($other)
			{
				$where.=" AND (groupid like '%".$other."%' or destination like '%".$other."%' )";
				$this->tpl->assign("other",$other);
			}
		}elseif($st == 3){
				//调拨编号
			$other = trim($this->input->get('other'));
			if($other)
			{
				$demand_number = $this->fun->getdatabasesdetail("t_oversea_demand"," AND demand_number ='".$other."'",'planning_id');
				if($demand_number["planning_id"])
				{
					$planning_id = trim(implode(",",explode("|",$demand_number["planning_id"])),",");
					$where.=" AND id in($planning_id)";
				}else{
					$where.=" AND id = '1111111111'";
				}
					$this->tpl->assign("other",$other);

			}
		}else{
			$other = trim($this->input->get('other'));
			if($other)
			{
				$where.=" AND (goodslist like '%".$other."%')";
				$this->tpl->assign("other",$other);
			}
		
		}
		if($this->input->get('id'))
		{
			$where.=" AND id='".$this->input->get('id')."'";
		}
		if($this->input->get('user'))
		{
			$where.=" AND createoper='".trim($this->input->get('user'))."'";
			$this->tpl->assign("usernamedispname",$this->input->get('user'));
		}
		if($this->input->get('status'))
		{
			if($this->input->get('status') == 6)
			{
				$where= " AND status = 7 ";
			}else{
				$where.=" AND status='".$this->input->get('status')."'";
			}
			$this->tpl->assign("status",$this->input->get('status'));
		}
		$endhouse =trim($this->input->get('endhouse'));
		if($endhouse)
		{
			$where.=" AND destination='".$endhouse."'";
			$this->tpl->assign("endhouse",$endhouse);
		}
		$starthouse =trim($this->input->get('starthouse'));
		if($starthouse)
		{
			$where.=" AND startingplace='".$starthouse."'";
			$this->tpl->assign("starthouse",$starthouse);
		}

		$shopname =trim($this->input->get('shopname'));
		if($shopname)
		{
			$where.=" AND shopname='".$shopname."'";
			$this->tpl->assign("shopname",$shopname);
		}
		$transportmode =trim($this->input->get('transportmode'));
		if($transportmode)
		{
			$where.=" AND transportmode='".$transportmode."'";
			$this->tpl->assign("transportmode",$transportmode);
		}
		
		$allnowbuynum=0;
		$list = $this->fun->getalllist('t_transportationplanning',$where,$nowpage,$if_csv,$this->pageSize);
		//echo $this->db->last_query();
		foreach($list["list"] as $key=>$rs)
		{
			$where = " AND id = '".$rs["oversearproduct_id"]."'";
			$detail = $this->fun->getdatabasesdetail('t_overseaproduct',$where);
			$list["list"][$key]["goods"] = $detail;
			
			$packingman = explode("|",$this->config->item('packingman'));
			
			if(in_array($_COOKIE["username"],$packingman))
			{
				$list["list"][$key]["mods"] = 1;	//封箱人员权限
			}else{
				$list["list"][$key]["mods"] = 0;
			}

			$isfile = $this->fun->getdatabasesdetail("t_oversea_file"," AND tpid = '".$rs['id']."'");
			if($isfile)
			{
				$list["list"][$key]["isfile"] = 1;
			}else{
				$list["list"][$key]["isfile"] = 0;
			}
			if($_COOKIE["username"] == $rs["createoper"])
			{
				$list["list"][$key]["mod"] = 1;
			}else{
				$list["list"][$key]["mod"] = 0;
			}

			if($st==2 && $other)
			{
				$where=" AND sku like '%".trim($other)."%' AND planid = '".$rs['id']."'";
				$restransportlist=$this->fun->getdatabasesdetail('t_transportlist',$where,' SUM(nowbuynum) as allnowbuynum');
				$allnowbuynum = $allnowbuynum+$restransportlist["allnowbuynum"];

			}
		}
		
		
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		$this->tpl->assign("department",$_COOKIE["department"]);
		if($allnowbuynum>0){
			$this->tpl->assign("allnowbuynum","SKU:".$other ." 实际封箱数量：".$allnowbuynum);
		}
		$this->tpl->assign("username",$_COOKIE["username"]);

		if($_COOKIE["shopname"])
		{
			//$shopname = unserialize($_COOKIE["shopname"]);
			//$this->tpl->assign("myshopname",$shopname);	
		}
		if($_COOKIE["seawarehouse"])
		{
			$seawarehouse = unserialize($_COOKIE["seawarehouse"]);
			$this->tpl->assign("myseawarehouse",$seawarehouse);	
		}
		$this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop','AND openflag= 1','id,name',' order by name asc'));			//查所有店铺
		//查所有仓库
		$this->tpl->assign("overseawarehouse", $this->fun->getdatabaseslist('t_overseawarehouse',' AND yz=0','id,name',' order by paixu asc'));
		if($this->config->item('transportmodelist')){
		 $transportmodelist = explode("|",$this->config->item('transportmodelist'));
		 $this->tpl->assign("transportmodelist",$transportmodelist);
		}

		//所有人员
		 $this->tpl->assign("userlist",$this->fun->getdatabaseslist('d_user'," AND type= 1"));
		$this -> tpl -> display("oversea/deliveryplanlist.tpl");
	}
	public function compare($id)
	{
		$where = " AND id = '".$id."'";
		$detail = $this->fun->getdatabasesdetail('t_transportationplanning',$where);
		$newgoodslist = unserialize($detail["goodslist"]);

		
		$goodslist = $newgoodslist['sku']; 
		foreach($goodslist as $key=>$rs)
		{
			$where = " AND sku = '".trim($rs)."'";
			$res=$this->fun->getdatabasesdetail('t_overseaproduct',$where,' id,sku,name,weight,costprice,lengthnum,widthnum,heightnum,volumenum,st');
		
			$goodsdata[$key] = $res;
			$goodsdata[$key]["sendnums"] = $newgoodslist["sendnums"][$key];
			$goodsdata[$key]["totalprice"] = $res["costprice"]* $newgoodslist["sendnums"][$key];
		}
		
		
		$this->tpl->assign("detail",$detail);

		
		$detaillist = unserialize($detail["detaillist"]);
		
		$showdetail = 0;
		foreach($detaillist as $key=>$rs)
		{
			$res=$this->fun->getdatabasesdetail('t_transportlist'," AND pid='".$rs["pid"]."' AND planid='".$id."'",'sum(nowbuynum) as lastnowbuynum');
			$detaillist[$key]["lastnowbuynum"] = $rs["sendnums"] - $res["lastnowbuynum"];
			if($detaillist[$key]["lastnowbuynum"]>0)
			{
				$showdetail = 1;
			}

			$skuname = $this->fun->getdatabasesdetail('t_overseaproduct'," AND sku='".$rs["sku"]."'");
			$detaillist[$key]["name"] = $skuname["name"];
			$detaillist[$key]["st"] = $skuname["st"];
			$detaillist[$key]["sku"] = $skuname["sku"];
		
		}
		if($detail["status"]==4)
		{
			$showdetail = 0;
		}
		$this->tpl->assign("showdetail",$showdetail);
		//die;
		$detaillist = $this->fun->multi_array_sort($detaillist,"sku");
		$this->tpl->assign("detaillist",$detaillist);//这里需要判断是否之前有发过货，发过则不显示
		$this->tpl->assign("goodsdata",$goodsdata);
		
		//生成箱号
		$this->tpl->assign("boxnumber",$this->m->getboxnumber());
		
		if($this->config->item('cartons')){	//系统设置的箱子规格
		 $cartons = explode("\r\n",$this->config->item('cartons'));
		 $this->tpl->assign("cartons",$cartons);
		}

		//箱子列表
		$boxlist= $this->fun->getdatabaseslist('t_transportbox'," AND planid='".$id."'");
		$this->tpl->assign("boxlistcount",count($boxlist));
		$this->tpl->assign("boxlist",$boxlist);

		$this -> tpl -> display("oversea/compare.tpl");
	}

	public function savecompare()
	{
		$id = $this->m->savecompare();
		header("location:/oversea/compare/{$id}");
	}
	public function cargostatus($id)
	{
		
		$boxlist= $this->fun->getdatabaseslist('t_transportlist A left join t_transportationtask B on A.taskid = B.id'," AND pid='".$id."'");
	
		$this->tpl->assign("boxlistcount",count($boxlist));
		$this->tpl->assign("boxlist",$boxlist);

		$this -> tpl -> display("oversea/cargostatus.tpl");
	}
	public function showcompare($id)
	{
		$res=$this->fun->getdatabasesdetail('t_transportbox'," AND id='".$id."'");
		$boxlist= $this->fun->getdatabaseslist('t_transportlist A left join t_overseapurchasing B on A.pid = B.id'," AND transportbox_id='".$id."'");
		$this->tpl->assign("boxlistcount",count($boxlist));
		$this->tpl->assign("boxlist",$boxlist);
		$this->tpl->assign("detail",$res);

		$this -> tpl -> display("oversea/showcompare.tpl");
	}
	public function undo($id,$plansid)
	{
		//撤销打包信息
		$transportlist= $this->fun->getdatabaseslist('t_transportlist'," AND transportbox_id='".$id."'",'id,pid,nowbuynum,planid,ist,sku');
	
		if(!$transportlist)
		{
			$this->db->query("DELETE FROM t_transportbox WHERE id='".$id."'");
		}
		foreach($transportlist as $key=>$rs)
		{
			$pid = $rs["pid"];
			$rsdb = $this->fun->getdatabasesdetail('t_overseapurchasing'," AND id='".$pid."'");
			$nums = $rsdb["actualdelivery"] - $rs["nowbuynum"];
			if($nums<=0)
			{
				$wheresql =" ,status = 0";
			}
			

		
			


			$this->db->query("UPDATE t_overseapurchasing SET actualdelivery='$nums' $wheresql where id='".$pid."' ");	//先撤销实际发货数
			$this->db->query("DELETE FROM t_transportlist WHERE id='".$rs["id"]."'");
			$this->db->query("DELETE FROM t_transportbox WHERE id='".$id."'");

			if($rs["ist"]==1)		//如果有凑箱的，需要去除
			{
				$ressku = $this->fun->getdatabasesdetail('t_overseaproduct'," AND sku='".$rs["sku"]."'");
				$price = $ressku["costprice"]*$rs["nowbuynum"];
				$atcnum = $rs["nowbuynum"];
				$this->db->query(" UPDATE t_transportationplanning SET totalnum =totalnum-$atcnum ,totalamount=totalamount-$price where id='".$rs["planid"]."'");	//凑箱的情况下更新总表数量
			}
		}
		header("location:/oversea/compare/{$plansid}");
	}
	
	public function showplan($id)
	{

		$where = " AND id = '".$id."'";
		$detail = $this->fun->getdatabasesdetail('t_transportationplanning',$where);
		
		$newgoodslist = unserialize($detail["goodslist"]);
		
		$goodslist = $newgoodslist['sku']; 
	
		foreach($goodslist as $key=>$rs)
		{
			$where = " AND sku = '".trim($rs)."'";
			$res=$this->fun->getdatabasesdetail('t_overseaproduct',$where,' id,sku,name,weight,costprice,lengthnum,widthnum,heightnum,volumenum');

		
			$goodsdata[$key] = $res;
			$goodsdata[$key]["sendnums"] = $newgoodslist["sendnums"][$key];
			$goodsdata[$key]["totalprice"] = $res["costprice"]* $newgoodslist["sendnums"][$key];
		}
		//计算耗材价格
		$boxlistcos= $this->fun->getdatabasesdetail('t_transportbox'," AND planid='".$id."'","sum(cartonscost) as costpirce");
		$costpe= $this->fun->getdatabasesdetail('t_transportbox'," AND planid='".$id."'","count(cartonscost) as costpe");
		$detail["boxlistcos"] = $boxlistcos["costpirce"];
		$detail["boxlistcount"] = $costpe["costpe"];
			
		
		$statuslist= $this->fun->getdatabaseslist('t_transport_status'," AND planid='".$id."'");
		if($this->config->item('transportmodelist')){
		 $transportmodelist = explode("|",$this->config->item('transportmodelist'));
		 $this->tpl->assign("transportmodelist",$transportmodelist);
		}
		if($this->config->item('carrierlist')){
		 $carrierlist = explode("|",$this->config->item('carrierlist'));
		 $this->tpl->assign("carrierlist",$carrierlist);
		}
		$this->tpl->assign("statuslist",$statuslist);
		$this->tpl->assign("detail",$detail);
		$this->tpl->assign("detaillist",$detaillist);//这里需要判断是否之前有发过货，发过则不显示
		$this->tpl->assign("goodsdata",$goodsdata);
		$this->tpl->assign("department",$_COOKIE["department"]);
		
		//$boxlist= $this->fun->getdatabaseslist('t_transportlist A left join t_overseapurchasing B on A.pid = B.id'," AND planid='".$id."'");
		
		//$this->tpl->assign("boxlistcount",count($boxlist));
		//$this->tpl->assign("boxlist",$boxlist);


		$this -> tpl -> display("oversea/showplan.tpl");
	}
	

	public function demandList()
	{
		$id = $this->input->get('id');
		$detail = $this->fun->getdatabasesdetail('t_oversea_demand'," AND id = '".$id."'");
		if($detail["planning_id"])
		{
			$planning_id = explode("|",trim($detail["planning_id"],"|"));
			$planning_id = implode(",",$planning_id);

			$planning = $this->db->get_where("t_transportationplanning","id in($planning_id) AND status !=6")->result_array();
			$this->tpl->assign("planning",$planning);
		}

		$list = $this->db->get_where("t_overseapurchasing","demandID = '".$id."'")->result_array();
		foreach($list as $key=>$rs)
		{
			$goods = $this->fun->getdatabasesdetail("db_goods"," and goods_sku='".$rs["goodsno"]."'");
			$list[$key]["name"] = $goods["goods_name"];
			$list[$key]["weight"] = round($goods["g_weight"]/1000,2);
			$costprice = $this->fun->get_Goods_costprice($rs["goodsno"]);
			$list[$key]["costprice"] = $costprice;
			$list[$key]["totalprice"] = $costprice * $rs["skunum"];
		}
		$this->tpl->assign("detail",$detail);
		$this->tpl->assign("goodsdata",$list);
			//一审人员和二审人员
		$firsttrial = $this->config->item('firsttrial');//一审人员
		if($firsttrial){
			$firsttrial = explode("|",$firsttrial);
			foreach($firsttrial as $rs)
			{
				if(trim($_COOKIE["username"]) == trim($rs))
				{
					$this->tpl->assign("firsttrialman",1);
				}
			}
		}else{
			$this->tpl->assign("firsttrialman",0);
		}

		$secondtrial = $this->config->item('secondtrial');//二审人员

		if($secondtrial){
			$secondtrial = explode("|",$secondtrial);

			foreach($secondtrial as $rs)
			{
				if($_COOKIE["username"] == $rs)
				{
					$this->tpl->assign("secondtrialman",1);
				}
			}
		}else{
			 $this->tpl->assign("secondtrialman",$_COOKIE["department"]);
		}
	
		$this -> tpl -> display("oversea/demandList.tpl");
	}


	public function showplandetail($id,$csv=0)
	{
		$where = " AND id = '".$id."'";
		$totalamount = 0;
		$detail = $this->fun->getdatabasesdetail('t_transportationplanning',$where);
		$newgoodslist = unserialize($detail["goodslist"]);
		$goodslist = $newgoodslist['sku'];
		$costpricelist = $newgoodslist['costprice'];
		$detaillist = unserialize($detail["detaillist"]);
		
		
		
		foreach($detaillist as $key=>$rs)
		{
			$where = " AND sku = '".trim($rs["sku"])."'";
			$res=$this->fun->getdatabasesdetail('t_overseaproduct',$where,' id,sku,name,weight,costprice,st');
			$goodsdata[$key] = $res;
			$goodsdata[$key]["sendnums"] = $newgoodslist["sendnums"][$key];
			$goodsdata[$key]["totalprice"] = $costpricelist[$key]* $newgoodslist["sendnums"][$key];
			$where=" AND sku='".trim($rs["sku"])."' AND planid = '".$id."'";
			$restransportlist=$this->fun->getdatabasesdetail('t_transportlist',$where,' SUM(nowbuynum) as allnowbuynum');
			$goodsdata[$key]["shifa"] = $restransportlist["allnowbuynum"];
			$goodsdata[$key]["wfa"] = $newgoodslist["sendnums"][$key] - $restransportlist["allnowbuynum"];
			$goodsdata[$key]["costprice"] = $costpricelist[$key];
			$rgoods = $this->fun->getdatabasesdetail('db_goods_stock A LEFT JOIN db_goods B on A.goods_id = B.goods_id',"  AND B.goods_sku = '".$res['sku']."'","positions");
			if($rgoods['positions'])
			{
				$goodsdata[$key]["positions"] = $rgoods['positions'];
			}

			$fnsku = $this->fun->getdatabasesdetail('t_overseapurchasing'," AND id = '".$rs["pid"]."'",' fnsku');
			$goodsdata[$key]["fnsku"] = $fnsku['fnsku'];
		}
		$goodsdata = $this->fun->multi_array_sort($goodsdata,"sku");
		//print_r($goodsdata);
		$boxlist= $this->fun->getdatabaseslist('t_transportbox'," AND planid='".$id."'");
		foreach($boxlist as $key=>$rs)
		{
			if($rs["task_id"]>0)
			{
				$detailtask = $this->fun->getdatabasesdetail('t_transportationtask'," AND id='".$rs["task_id"]."'");
				if($detailtask)
				{
					$boxlist[$key]["taskstatus"] = $detailtask["status"];
				}
			}else{
				$boxlist[$key]["taskstatus"] = 0;
			}
		}
		$this->tpl->assign("boxlistcount",count($boxlist));
		$this->tpl->assign("boxlist",$boxlist);

		$this->tpl->assign("detail",$detail);
		$this->tpl->assign("goodsdata",$goodsdata);
			//一审人员和二审人员
		$firsttrial = $this->config->item('firsttrial');//一审人员
		if($firsttrial){
			$firsttrial = explode("|",$firsttrial);
			foreach($firsttrial as $rs)
			{
				if(trim($_COOKIE["username"]) == trim($rs))
				{
					$this->tpl->assign("firsttrialman",1);
				}
			}
		}else{
			$this->tpl->assign("firsttrialman",0);
		}

		$secondtrial = $this->config->item('secondtrial');//二审人员

		if($secondtrial){
			$secondtrial = explode("|",$secondtrial);

			foreach($secondtrial as $rs)
			{
				if($_COOKIE["username"] == $rs)
				{
					$this->tpl->assign("secondtrialman",1);
				}
			}
		}else{
			 $this->tpl->assign("secondtrialman",$_COOKIE["department"]);
		}
	
		if($csv==1)
		{
			
				$filename = $detail["groupid"]."-".date('Ymd') . '.csv';
				header("Content-type: text/csv");
				header("content=text/html;charset=utf8");
				header("Content-Disposition: attachment; filename=" . $filename);
				header('Cache-Control: must-revalidate,post-check=0,pre-check=0');
				header('Expires:0');
				header('Pragma:public');
				$str = "运输编号,运输方式,店铺,始发地,目的地,SKU数,数量\r\n";
				$pattern = '/(,)+/i';
					$str .= "" . $detail["groupid"].",".$detail["transportmode"].",".$detail["shopname"]."," . $detail["startingplace"]."," . $detail["destination"].",".$detail["skunum"].",".$detail["totalnum"]."\r\n\r\n\r\n\r\n\r\n\r\n";
				$str.= "SKU,FNSKU,商品名称,计划发货数,发货数,未发货数,仓位\r\n";
				  foreach ($goodsdata as $v) {
					if($v["fnsku"]=='')
					 {
						$fnsku = $this->fun->getdatabasesdetail("t_overseapurchasing"," and goodsno='".$v["sku"]."' AND shopname ='".$detail["shopname"]."' AND fnsku !='' ",'fnsku');
						$v["fnsku"] = $fnsku["fnsku"];
					}

					$str .= "" . $v["sku"].",".$v["fnsku"].",".$v["name"]."," . $v["sendnums"].",".$v["shifa"].",".$v["wfa"].",".$v["positions"]."\r\n";
				  }
				  echo mb_convert_encoding($str, "cp936", "UTF-8");
				  exit();
		}


		$this -> tpl -> display("oversea/showplandetail.tpl");
	}

	public function showbox($id)
	{
		$boxlist= $this->fun->getdatabaseslist('t_transportlist'," AND transportbox_id='".$id."'");
		foreach($boxlist as $key=>$rs)
		{
			$res=$this->fun->getdatabasesdetail('t_overseaproduct'," AND id ='".$rs['skuid']."'",' id,sku,name,weight,costprice,st');
			$boxlist[$key]['sku'] = $res['sku'];
		}
		$this->tpl->assign("boxlist",$boxlist);
		$this -> tpl -> display("oversea/showbox.tpl");
	}
	public function showtask($id)
	{
		$sn = trim($this->input->get('sn'));
		if($sn)
		{
			$where = " AND tasknumber = '".$sn."'";
		}else{
			$where = " AND id = '".$id."'";
		}
		$detail = $this->fun->getdatabasesdetail('t_transportationtask',$where);
		
		    if($_COOKIE["username"] == $detail["createoper"])
			{
			   $this->tpl->assign("mod",1);
			}else{
				 $this->tpl->assign("mod",0);
			}
		//$newgoodslist = unserialize($detail["goodslist"]);
	
		//$goodslist = $newgoodslist['sku']; 
	
		
		//计算耗材价格
		$boxlistcos= $this->fun->getdatabasesdetail('t_transportbox'," AND task_id='".$id."'","sum(cartonscost) as costpirce");
		$costpe= $this->fun->getdatabasesdetail('t_transportbox'," AND task_id='".$id."'","count(cartonscost) as costpe");
		$detail["boxlistcos"] = $boxlistcos["costpirce"];
		$detail["boxlistcount"] = $costpe["costpe"];
			
		
		$statuslist= $this->fun->getdatabaseslist('t_transport_status'," AND task_id='".$id."'");
		if($this->config->item('transportmodelist')){
		 $transportmodelist = explode("|",$this->config->item('transportmodelist'));
		 $this->tpl->assign("transportmodelist",$transportmodelist);
		}
		if($this->config->item('carrierlist')){
		 $carrierlist = explode("|",$this->config->item('carrierlist'));
		 $this->tpl->assign("carrierlist",$carrierlist);
		}
		
			if($detail["actual_freight"])
			{
				$freigth = $detail["actual_freight"];
			}else{
				$freigth = $detail["freight"];
			}
		$detail["total"] = $detail["totalamount"] + $detail["boxlistcos"] + $freigth;
		$this->tpl->assign("statuslist",$statuslist);
		$this->tpl->assign("detail",$detail);
		$this->tpl->assign("detaillist",$detaillist);//这里需要判断是否之前有发过货，发过则不显示
		$this->tpl->assign("goodsdata",$goodsdata);
		$this->tpl->assign("department",$_COOKIE["department"]);
		
		$boxlist= $this->fun->getdatabaseslist('t_transportbox'," AND task_id='".$id."'");
		$this->tpl->assign("boxlistcount",count($boxlist));
		$this->tpl->assign("boxlist",$boxlist);
		$this->tpl->assign("sfexpress", $this->config->item('sfexpress_oversea'));
		$this->tpl->assign("upsexpress", $this->config->item('upsexpress_oversea'));
		$this->tpl->assign("dhlexpress", $this->config->item('dhlexpress_oversea'));
		$this->tpl->assign("FedExexpress", $this->config->item('FedExexpress_oversea'));

		$this->tpl->assign("jiachenexpress", $this->config->item('jiachenExexpress_oversea'));

		$this->tpl->assign("department", $_COOKIE["department"]);
		$this -> tpl -> display("oversea/showtask.tpl");
	}
	public function editshowplan($id)
	{
		$where = " AND id = '".$id."'";
		$detail = $this->fun->getdatabasesdetail('t_transportationplanning',$where);
		
		$newgoodslist = unserialize($detail["goodslist"]);
		
		$goodslist = $newgoodslist['sku']; 
	
		foreach($goodslist as $key=>$rs)
		{
			$where = " AND sku = '".trim($rs)."'";
			$res=$this->fun->getdatabasesdetail('t_overseaproduct',$where,' id,sku,name,weight,costprice,lengthnum,widthnum,heightnum,volumenum,st');

		
			$goodsdata[$key] = $res;
			$goodsdata[$key]["sendnums"] = $newgoodslist["sendnums"][$key];
			$goodsdata[$key]["totalprice"] = $res["costprice"]* $newgoodslist["sendnums"][$key];
		}
		$this->tpl->assign("detail",$detail);
		$this->tpl->assign("detaillist",$detaillist);//这里需要判断是否之前有发过货，发过则不显示
		$this->tpl->assign("goodsdata",$goodsdata);
		$this->tpl->assign("department",$_COOKIE["department"]);

		if($this->config->item('transportmodelist')){
		 $transportmodelist = explode("|",$this->config->item('transportmodelist'));
		 $this->tpl->assign("transportmodelist",$transportmodelist);
		}
		if($this->config->item('carrierlist')){
		 $carrierlist = explode("|",$this->config->item('carrierlist'));
		 $this->tpl->assign("carrierlist",$carrierlist);
		}
		if(strstr($detail['destination'],"Amazon"))
		{
			$this->tpl->assign("showfile",1);
		}else{
			$this->tpl->assign("showfile",0);
		}

		$this -> tpl -> display("oversea/editshowplan.tpl");
	}
	public function transportlist()
	{
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;
		
		if($_COOKIE["department"]==1 || $_COOKIE["department"]==2)
		{
		
		}else{
			//$where = " AND createoper='".$_COOKIE["username"]."'";
		}
		

		if($_COOKIE['classid']==14)
		{
			if($_COOKIE["shopname"])
			{
				$shopname = unserialize($_COOKIE["shopname"]);
				$shopname = implode("','",$shopname);
				$where.=" AND shopname in ('".$shopname."')";
			}
		
		}else{

		}



		//$where.=" AND (status=4 or status=5)";
		$starttime =trim($this->input->get('starttime'));
		if($starttime)
		{
			$where.=" AND createtime >='".$starttime."'";
			$this->tpl->assign("starttime",$starttime);
		}
		$endtime =trim($this->input->get('endtime'));
		if($endtime)
		{
			$where.=" AND createtime <='".$endtime."'";
			$this->tpl->assign("endtime",$endtime);
		}
		$other = $this->input->get('other');

		if($other)
		{
			if($this->input->get('st')==1)
			{
				$where.=" AND (tasknumber like '%".$other."%' or shopname like '%".$other."%' )";
			}elseif($this->input->get('st')==3)
			{
				$where.= " AND id in(SELECT task_id FROM t_transport_status WHERE ck like '".trim($this->input->get_post('other'))."')";
			}else{
				$where.= " AND id in(SELECT taskid FROM t_transportlist WHERE sku like '".trim($this->input->get_post('other'))."')";
			}

			$this->tpl->assign("st",$this->input->get('st'));
			$this->tpl->assign("other",$other);
		}
		$endhouse =trim($this->input->get('endhouse'));
		if($endhouse)
		{
			$where.=" AND destination='".$endhouse."'";
			$this->tpl->assign("endhouse",$endhouse);
		}
			$starthouse =trim($this->input->get('starthouse'));
		if($starthouse)
		{
			$where.=" AND startingplace='".$starthouse."'";
			$this->tpl->assign("starthouse",$starthouse);
		}

		$shopname =trim($this->input->get('shopname'));
		if($shopname)
		{
			$where.=" AND shopname='".$shopname."'";
			$this->tpl->assign("shopname",$shopname);
		}
		if($this->input->get('status'))
		{
			$where.=" AND status='".$this->input->get('status')."'";
			$this->tpl->assign("status",$this->input->get('status'));
		}
		if($this->input->get('carrier'))
		{
			$where.=" AND carrier='".$this->input->get('carrier')."'";
			$this->tpl->assign("carrier",$this->input->get('carrier'));
		}
		$orderby = " order by id DESC";
		//导出excel
		if(trim($this->input->get_post('flagtype'))==1){
			require dirname(__FILE__)."/../../fuman/ClassesExcel/PHPExcel.php";
			$objExcel = new PHPExcel();
			$where ="SELECT * FROM t_transportationtask where 1 ".$where;
			$result = $this->db->query($where)->result_array();

			$objExcel->setActiveSheetIndex(0);
			$objExcel->getActiveSheet()->getDefaultRowDimension()->setRowHeight(15);
			$objExcel->getActiveSheet()->getColumnDimension('A')->setWidth(10);
			$objExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
			$objExcel->getActiveSheet()->getColumnDimension('C')->setWidth(12);
			$objExcel->getActiveSheet()->getColumnDimension('D')->setWidth(12);
			$objExcel->getActiveSheet()->getColumnDimension('E')->setWidth(10);
			$objExcel->getActiveSheet()->getColumnDimension('F')->setWidth(10);
			$objExcel->getActiveSheet()->getColumnDimension('G')->setWidth(30);
			$objExcel->getActiveSheet()->getColumnDimension('H')->setWidth(15);
			$objExcel->getActiveSheet()->getColumnDimension('I')->setWidth(15);
			$objExcel->getActiveSheet()->getColumnDimension('J')->setWidth(15);
			$objExcel->getActiveSheet()->getColumnDimension('K')->setWidth(15);
			$objExcel->getActiveSheet()->getColumnDimension('L')->setWidth(15);

			//设置标题
			$objExcel->setActiveSheetIndex(0)->setCellValue('A1','任务编号');
			$objExcel->setActiveSheetIndex(0)->setCellValue('B1','计划号');
			$objExcel->setActiveSheetIndex(0)->setCellValue('C1','创建时间');
			$objExcel->setActiveSheetIndex(0)->setCellValue('D1','店铺名');
			$objExcel->setActiveSheetIndex(0)->setCellValue('E1','始发仓');
			$objExcel->setActiveSheetIndex(0)->setCellValue('F1','承运人');
			$objExcel->setActiveSheetIndex(0)->setCellValue('G1','物流');
			$objExcel->setActiveSheetIndex(0)->setCellValue('H1','运单号');
			$objExcel->setActiveSheetIndex(0)->setCellValue('I1','预估物流费');
			$objExcel->setActiveSheetIndex(0)->setCellValue('J1','真实物流费');
			$objExcel->setActiveSheetIndex(0)->setCellValue('K1','包装成本');
			$objExcel->setActiveSheetIndex(0)->setCellValue('L1','头程总费用');


			foreach($result as $k=>$v){

				$detailtask= $this->fun->getdatabasesdetail('t_transportlist'," AND tasknumber='".$v["tasknumber"]."'");
				$detailplan= $this->fun->getdatabasesdetail('t_transportationplanning'," AND id='".$detailtask["planid"]."'");

				$deliver= $this->fun->getdatabasesdetail('t_transport_status'," AND task_id='".$v["id"]."'","GROUP_CONCAT(transportmode) as transportmode,GROUP_CONCAT(ck) as ck,GROUP_CONCAT(carrier) as carrier");


				$head_fee = $v['totalmoney'] + $v['actual_freight'];
				$count = $k+2;
				$objExcel->setActiveSheetIndex(0)->setCellValue('A'.$count,$v['tasknumber']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('B'.$count,$detailplan['groupid']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('C'.$count,$v['createtime']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('D'.$count,$v['shopname']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('E'.$count,$v['startingplace']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('F'.$count,$deliver['carrier']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('G'.$count,$deliver['transportmode']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('H'.$count,$deliver['ck']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('I'.$count,$v['freight']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('J'.$count,$v['actual_freight']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('K'.$count,$v['totalmoney']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('L'.$count,$head_fee);

			}
			$excel_name = date("YmdHis");
			header("Content-type:application/vnd.ms-excel;charset=gb2312");
			header('Content-Disposition: attachment;filename="'.$excel_name.'.xls"');
			header('Cache-Control: max-age=0');
			$objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
			$objWriter->save('php://output');
			exit;
		}

		$list = $this->fun->getalllist('t_transportationtask',$where,$nowpage,$if_csv,$this->pageSize,$orderby);

		foreach($list["list"] as $key=>$rs)
		{
			$where = " AND id = '".$rs["oversearproduct_id"]."'";
			$detail = $this->fun->getdatabasesdetail('t_overseaproduct',$where);
			$list["list"][$key]["goods"] = $detail;

			//查询仓库 鉴别海外仓

			//出发地仓库
			$sql_start = "SELECT * FROM t_overseawarehouse WHERE yz = 0 AND name = '{$rs['startingplace']}' ";
			$rs_start  = $this->db->query($sql_start)->row_array();
			$list["list"][$key]["oversea_startId"] = $rs_start['id'];

			//目的地仓库
			$sql_destination = "SELECT * FROM t_overseawarehouse WHERE yz = 0 AND name = '{$rs['destination']}' ";
			$rs_destination  = $this->db->query($sql_destination)->row_array();
			$list["list"][$key]["oversea_destinationId"] = $rs_destination['id'];

			//查看是否有运输状态
			$detailstatus = $this->fun->getdatabasesdetail('t_transport_status'," AND task_id='".$rs["id"]."'");
			if(!$detailstatus)
			{
				$list["list"][$key]["tstatus"] =1;
			}else{
				$list["list"][$key]["tstatus"] =0;
			}

			if($_COOKIE["username"] == $rs["createoper"])
			{
				$list["list"][$key]["mod"] = 1;
			}else{
				$list["list"][$key]["mod"] = 0;
			}
			if($rs["actual_freight"])
			{
				$freigth = $rs["actual_freight"];
			}else{
				$freigth = $rs["freight"];
			}
			$list["list"][$key]["total"] =  $rs["totalamount"] + $rs["totalmoney"] + $freigth;
			

		}
		
		
	
		if($this->config->item('carrierlist')){
		 $carrierlist = explode("|",$this->config->item('carrierlist'));
		 $this->tpl->assign("carrierlist",$carrierlist);
		}
		if($this->config->item('transportmodelist')){
		 $transportmodelist = explode("|",$this->config->item('transportmodelist'));
		 $this->tpl->assign("transportmodelist",$transportmodelist);
		}
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		
//		if($_COOKIE["shopname"])
//		{
//			$shopname = unserialize($_COOKIE["shopname"]);
//			$this->tpl->assign("myshopname",$shopname);	
//		}
		if($_COOKIE["seawarehouse"])
		{
			$seawarehouse = unserialize($_COOKIE["seawarehouse"]);
			$this->tpl->assign("myseawarehouse",$seawarehouse);	
		}
		$this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop','AND openflag= 1','id,name',' order by name asc'));			//查所有店铺
		//查所有仓库
		$this->tpl->assign("overseawarehouse", $this->fun->getdatabaseslist('t_overseawarehouse',' AND yz=0','id,name',' order by paixu asc'));
		//海外仓
		$this->tpl->assign("arr_oversea",array(3,4,6,9));

		$this->tpl->assign("sfexpress", $this->config->item('sfexpress_oversea'));
		$this->tpl->assign("upsexpress", $this->config->item('upsexpress_oversea'));
		$this->tpl->assign("dhlexpress", $this->config->item('dhlexpress_oversea'));
		$this->tpl->assign("FedExexpress", $this->config->item('FedExexpress_oversea'));
		$this->tpl->assign("jiachenexpress", $this->config->item('jiachenExexpress_oversea'));

		$this->tpl->assign("department", $_COOKIE["department"]);
		$this -> tpl -> display("oversea/transportlist.tpl");
	}
		
	public function report()
	{	
		
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;
		
		
		$s2 = $this->input->get('s2');
		$s1 = $this->input->get('s1');
		$s5 = $this->input->get('s5');
		if($s2)$status[] = $s2;
		if($s1)$status[] = $s1;
		if($s5)$status[] = $s5;
		if($status){
				$where = " AND (";
			foreach($status as $key => $r)
			{
				if($key>0)$or = " or ";
				$where.=" $or B.status = $r";
				if($r==2)$this->tpl->assign("s2",2);
				if($r==1)$this->tpl->assign("s1",1);
				if($r==5)$this->tpl->assign("s5",5);
			}
			$where.=")";
		}else{
			$where = " AND (";
			$where.=" B.status = 2 or B.status = 1)";
			$this->tpl->assign("s2",2);
			$this->tpl->assign("s1",1);
		}
		$other = $this->input->get('other');
		if($other)
		{
			$where.=" AND (A.sku like '%".$other."%' or B.tasknumber like '%".$other."%' )";
			$this->tpl->assign("other",$other);
		}
		$starttime =trim($this->input->get('starttime'));
		if($starttime)
		{
			$where.=" AND B.createtime >='".$starttime."'";
			$this->tpl->assign("starttime",$starttime);
		}
		$endtime =trim($this->input->get('endtime'));
		if($endtime)
		{
			$where.=" AND B.createtime <='".$endtime."'";
			$this->tpl->assign("endtime",$endtime);
		}
		$endhouse =trim($this->input->get('endhouse'));
		if($endhouse)
		{
			$where.=" AND B.destination ='".$endhouse."'";
			$this->tpl->assign("endhouse",$endhouse);
		}
		$sn =trim($this->input->get('sn'));
		if($sn)
		{
			$where.=" AND B.shopname ='".$sn."'";
			$this->tpl->assign("sn",$sn);
		}
		$orderbysku =  $this->input->get('orderbysku');
		if($orderbysku)
		{
			$orderby =" order by sku {$orderbysku}";
			if($orderbysku=='ASC')
			{
				$this->tpl->assign("orderbysku",'DESC');
			}else{
				$this->tpl->assign("orderbysku",'ASC');
			}

		}else{
			$orderby =" order by sku ASC";
			$this->tpl->assign("orderbysku",'DESC');
		}

		$list = $this->m->getreport($where,$nowpage,$if_csv,$this->pageSize,$orderby);
	
		foreach($list["list"] as $key=>$rs)
		{
			
			if($rs["costprice"])
			{
				$list["list"][$key]["price"] =$rs["costprice"]*$rs["amount_num"];
			}else{
				$list["list"][$key]["price"] =0;
			}

		}

		//计算统计数量
		$num = 0;
		$allprice = 0;
		foreach($list["alldates"] as $key=>$rs)
		{
			$sku[] = $rs["sku"];
			$num = $num+$rs["amount_num"];
			$allprice = $allprice+($rs["amount_num"]*$rs["costprice"]);
		}
		if($sku){
			$skunum = array_unique($sku);
		}

		
		

		$str = array("skunum"=>count($skunum),"num"=>$num,"allprice"=>$allprice,);

		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		$this->tpl->assign("str",$str);
		$this->tpl->assign("department", $_COOKIE["department"]);
		if($_COOKIE["seawarehouse"])
		{
			$seawarehouse = unserialize($_COOKIE["seawarehouse"]);
			$this->tpl->assign("myseawarehouse",$seawarehouse);	
		}
		$this->tpl->assign("overseawarehouse", $this->fun->getdatabaseslist('t_overseawarehouse',' AND yz=0','id,name',' order by paixu asc')); 
		

//		if($_COOKIE["shopname"])
//		{
//			$shopname = unserialize($_COOKIE["shopname"]);
//			
//			$this->tpl->assign("myshopname",$shopname);	
//		}
		$this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop','AND openflag= 1','id,name',' order by name asc'));			//查所有店铺
		$this -> tpl -> display("oversea/report.tpl");
	}

	public function transportboxtypelist()
	{
		$this->pageSize = 1000;
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;
		
		if($_COOKIE["department"]==1 || $_COOKIE["department"]==2)
		{
		
		}else{
			//$where = " AND createoper='".$_COOKIE["username"]."'";
		}
		$where.=" AND A.boxstatus=0";
		$starttime = trim($_POST["starttime"]);
		if($starttime)
		{
			$where.=" AND A.createtime >='".$starttime."'";
			$this->tpl->assign("starttime",$starttime);
		}
		$endtime =trim($this->input->post('endtime'));
		if($endtime)
		{
			$where.=" AND A.createtime <='".$endtime."'";
			$this->tpl->assign("endtime",$endtime);
		}
		$other = $this->input->post('other');
		if($other)
		{
			$where.=" AND (B.groupid like '%".$other."%' or B.destination like '%".$other."%' )";
			$this->tpl->assign("other",$other);
			
		}
		
		if($this->input->get('status'))
		{
			$where.=" AND status='".$this->input->get('status')."'";
		}
		$orderby = " order by A.id DESC";
		$list = $this->m->getboxtypelistlist('t_transportbox A left join t_transportationplanning B on A.planid=B.id',$where,$nowpage,$if_csv,$this->pageSize,$orderby);
		foreach($list["list"] as $key=>$rs)
		{
			$where = " AND id = '".$rs["oversearproduct_id"]."'";
			$detail = $this->fun->getdatabasesdetail('t_overseaproduct',$where);
			$list["list"][$key]["goods"] = $detail;
		}
		
		
		
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		$this -> tpl -> display("oversea/transportboxtypelist.tpl");
	}
	
	
	public function warehouse()
	{
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;

		$where ="";
		$other = $this->input->post('other');
		if($other)
		{
			$where.=" AND (name like '%".$other."%' )";
			$this->tpl->assign("other",$other);
		}
		$orderbysku =  $this->input->get('orderbysku');
		if($orderbysku)
		{
			$orderby =" order by paixu {$orderbysku}";
			if($orderbysku=='ASC')
			{
				$this->tpl->assign("orderbysku",'DESC');
			}else{
				$this->tpl->assign("orderbysku",'ASC');
			}

		}else{
			$orderby =" order by paixu ASC";
			$this->tpl->assign("orderbysku",'DESC');
		}

		$list = $this->fun->getalllist('t_overseawarehouse',$where,$nowpage,$if_csv,$this->pageSize,$orderby);
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list",$list["list"]);
		$this -> tpl -> display("oversea/warehouse.tpl");
	}
	public function syscenter()
	{
		$rsdb = $this->fun->getconfig();
		$this->tpl->assign("rsdb",$rsdb);
		$this -> tpl -> display("oversea/syscenter.tpl");
	}
	function saveconfig()
	{
		$webdbs = $this->input->post('webdbs');
		$this->fun->write_config_cache($webdbs);
		$url = $_SERVER['HTTP_REFERER'];
		header("location:{$url}");
	}
	public function transportboxtypedetail()
	{
		$uid = $this->input->get('uid');
		$uid =substr($uid,0,-1);
		$transportbox = $this->fun->getdatabaseslist('t_transportbox A left join t_transportationplanning B on A.planid=B.id'," AND A.id in($uid)",'B.groupid,B.id,B.destination,B.startingplace',' order by A.id desc');
		
		foreach($transportbox as $key=>$rs)
		{
			$id[] = $rs["id"];
		}
				

		$idnum= array_unique($id);
		if($idnum)
		{
			$id = $idnum[0];
		}
		$where = " AND id = '".$id."'";
		$detail = $this->fun->getdatabasesdetail('t_transportationplanning',$where);
		$detail["freight"] = unserialize($detail["freight"]);
		$detail["projectdateremake"] = unserialize($detail["projectdateremake"]);

		$newgoodslist = unserialize($detail["goodslist"]);
			
		if($detail["beiprojectdate"] =="0000-00-00")
		{
			$detail["beiprojectdate"] = date("Y-m-d");
		}
	
		$goodslist = $newgoodslist['sku']; 
		foreach($goodslist as $key=>$rs)
		{
			$where = " AND sku = '".trim($rs)."'";
			$res=$this->fun->getdatabasesdetail('t_overseaproduct',$where,' id,sku,name,weight,costprice,lengthnum,widthnum,heightnum,volumenum');

		
			$goodsdata[$key] = $res;
			$goodsdata[$key]["sendnums"] = $newgoodslist["sendnums"][$key];
			$goodsdata[$key]["totalprice"] = $res["costprice"]* $newgoodslist["sendnums"][$key];
		}


		$this->tpl->assign("detail",$detail);

			//自动生成申请编号
		$rsdb = $this->db->get_one("SELECT * FROM `t_transportationtask` WHERE 1 order by id DESC ");
		$tasknumber = trim($rsdb["tasknumber"]);
		$nums = substr($tasknumber,8);
		if($nums)
		{
			$Number=$nums+1;
			$orderID = "TT".date("ymd").$Number;
			$this->tpl->assign("orderID",$orderID);
		}
		
		
		$this->tpl->assign("goodsdata",$goodsdata);
		

		/*
		if($this->config->item('cartons')){	//系统设置的箱子规格
		 $cartons = explode("\r\n",$this->config->item('cartons'));
		 $this->tpl->assign("cartons",$cartons);
		}*/
		if($this->config->item('carrierlist')){
		 $carrierlist = explode("|",$this->config->item('carrierlist'));
		 $this->tpl->assign("carrierlist",$carrierlist);
		}

		if($this->config->item('transportmodelist')){
		 $transportmodelist = explode("|",$this->config->item('transportmodelist'));
		 $this->tpl->assign("transportmodelist",$transportmodelist);
		}
		
		
		if($_COOKIE["seawarehouse"])
		{
			$seawarehouse = unserialize($_COOKIE["seawarehouse"]);
			$this->tpl->assign("myseawarehouse",$seawarehouse);	
		}
		$this->tpl->assign("d_shop", $this->fun->getdatabaseslist('d_shop','AND openflag= 1','id,name',' order by name asc'));			//查所有店铺
		//查所有仓库
		$this->tpl->assign("overseawarehouse", $this->fun->getdatabaseslist('t_overseawarehouse',' AND yz=0','id,name','  order by paixu asc')); 
		//箱子列表
		$boxlist= $this->fun->getdatabaseslist('t_transportbox'," AND id in($uid)");

		$this->tpl->assign("boxlistcount",count($boxlist));
		$this->tpl->assign("boxlist",$boxlist);


		$this -> tpl -> display("oversea/transportboxtypedetail.tpl");
	}
	public function savetxtypedetail()
	{
		$plansid = $this->m->savetxtypedetail();
		header("location:/oversea/transportlist");
		
	}
    public function saveproduct()
	{
		$id=$this->m->saveproduct();
		header("location:/oversea/product?id=".$id);
	}
	public function savewarehouse()
	{
		$id=$this->m->savewarehouse();
		header("location:/oversea/warehouse?id=".$id);
	}
	
	public function addoverseaproduct()
	{
		$id = $this->input->get('id');
		if($id)
		{
			$where = " AND id='".$id."'";
			$res=$this->fun->getdatabasesdetail('t_overseaproduct',$where,'*');
		}
		$this->tpl->assign("detail",$res);
		$this -> tpl -> display("oversea/addoverseaproduct.tpl");
	}
	public function addwarehouse()
	{
		$id = $this->input->get('id');
		if($id)
		{
			$where = " AND id='".$id."'";
			$res=$this->fun->getdatabasesdetail('t_overseawarehouse',$where,'*');
		}
		$this->tpl->assign("detail",$res);
		$this -> tpl -> display("oversea/addwarehouse.tpl");
	}
	public function addstock()
	{
		
		$sku = $this->input->post('sku');
		$nums = $this->input->post('nums');
		if($sku =='')
		{
			die('请输入SKU！');
		}
		if($nums =='')
		{
			die('请输入数量！');
		}
		
		$this->db->trans_begin();
		$parentID = $this->m->savestockgrn(1);
		$goods_id = $this->m->savestockgoods($sku,$nums,$parentID);
		
		if ($this->db->trans_status() === FALSE)
		{
			$this->db->trans_rollback();
		}
		else
		{
			$this->db->trans_commit();
		}

		header("location:/oversea/addstocklist?id=".$parentID);
		
	}
	public function addstocklist()
	{
		$id = $this->input->get_post('id');
		
		$this->pageSize  =20;
		$nowpage = $_REQUEST["pageid"];
	    if ($nowpage == "")
            $nowpage = 1;
		$where = "";

		$type = $this->input->get_post('t');
		if($type=="")
		{
			$where.=" AND types = 1";
		}else{
			$where.=" AND types = {$type}";
		}
		$starttime = trim($this->input->get('starttime'));
		if($starttime)
		{
			$times = $starttime." 00:00:00";
			$where.=" AND (updatetime >= '".trim($times)."')";
			$this->tpl->assign("starttime",$starttime);
		}

		$endtime = trim($this->input->get('endtime'));
		if($endtime)
		{
			$times = $endtime." 23:59:59";
			$where.=" AND (updatetime <= '".trim($times)."')";
			$this->tpl->assign("endtime",$endtime);
		}
		$other = trim($this->input->get('other'));
		if($other)
		{
			$where.=" AND (orderno = '".$other."' )";
			$this->tpl->assign("other",$other);
		}
		$status = trim($this->input->get('status'));
		if($status)
		{
			if($status==2)
			{
				$s = 0;
			}else{
				$s = 1;
			}
			$where.=" AND (is_check = '".$s."' )";
			$this->tpl->assign("statuss",$status);
		}
	
		$orderby = " order by is_check ASC,id DESC";
		$list = $this->fun->getalllist('t_overseastock_grn',$where,$nowpage,$if_csv,$this->pageSize,$orderby);
		foreach($list["list"] as $key=>$rs)
		{
			$res = $this->fun->getdatabasesdetail('t_overseastock_goods' ,' AND orderno="'.$rs["orderno"].'"'," count(sku) as skunum");
			$list["list"][$key]["skunum"] = $res["skunum"];
			$res = $this->fun->getdatabasesdetail('t_overseastock_goods' ,' AND orderno="'.$rs["orderno"].'"'," SUM(stock) as stocknum");
			$list["list"][$key]["stocknum"] = $res["stocknum"];

			$info = $this->fun->userinfo($rs["createUid"]);
			$list["list"][$key]["username"] = $info["name"];
		}
		
		
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
        $this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
        $this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("list", $list["list"]);

		if($type==2)
		{
		$this -> tpl -> display("oversea/stockoutlist.tpl");
		}else
		$this -> tpl -> display("oversea/addstocklist.tpl");
	}
	//海外仓规则列表
	public function overseaRulesList(){
		$nowpage = $_REQUEST["pageid"];
		if ($nowpage == "") $nowpage = 1;
		$where = "";
		$orderby = " ORDER BY priority asc,opertime desc ";
		$list = $this->fun->getalllist("db_oversea_rules", $where, $nowpage, $if_csv, $this->pageSize, $orderby);
		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
		$this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
		$this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("orderlist", $list["list"]);
		$this->tpl->display("oversea/oversearuleslist.tpl");
	}
	public function addOverseaRules(){
		$id = intval($this->input->get('id'));
		if($id){
			$res = $this->fun->getdatabasesdetail("db_oversea_rules"," AND id='".$id."'");
			if($res["orderstatus"])
			{
				$res["orderstatus"] = explode(",",$res["orderstatus"]);
			}
		}else{
			$res["orderstatus"]  = array();
		}
		$express = $this->db->get_where("db_order_express","status=0")->result_array();
		$this->tpl->assign("express",$express);
		$this->tpl->assign("detail",$res);
		$this->tpl->display("oversea/addoversearules.tpl");
	}
	public function saveOverseaRules()
	{
		$this->m->saveOverseaRules();
		$this->fun->phpalert(4, "", '', "/oversea/overseaRulesList");
	}
	//海外仓账单
	public function showOverseaBill(){
		$nowpage = $_REQUEST["pageid"];
		if ($nowpage == "") $nowpage = 1;
		$where = "";
		//查询日期 若有时间，默认根据发货时间进行搜索
		$search_date = $this->input->get('search_date');
		if($search_date){
			$this->tpl->assign("search_date",$search_date);
			if($search_date==1){
				$starttime = trim($this->input->get('starttime'));
				if($starttime)
				{
					$times = $starttime." 00:00:00";
					$where.=" AND (a.dispatchTime >= '".$times."')";
					$this->tpl->assign("starttime",$starttime);
				}

				$endtime = trim($this->input->get('endtime'));
				if($endtime)
				{
					$times = $endtime." 23:59:59";
					$where.=" AND (a.dispatchTime <= '".$times."')";
					$this->tpl->assign("endtime",$endtime);
				}
			}
			if($search_date==2){
				$starttime = trim($this->input->get('starttime'));
				if($starttime)
				{
					$times = $starttime." 00:00:00";
					$where.=" AND (a.addTime >= '".$times."')";
					$this->tpl->assign("starttime",$starttime);
				}

				$endtime = trim($this->input->get('endtime'));
				if($endtime)
				{
					$times = $endtime." 23:59:59";
					$where.=" AND (a.addTime <= '".$times."')";
					$this->tpl->assign("endtime",$endtime);
				}
			}


		}else{
			$starttime = trim($this->input->get('starttime'));
			if($starttime)
			{
				$times = $starttime." 00:00:00";
				$where.=" AND (a.dispatchTime >= '".$times."')";
				$this->tpl->assign("starttime",$starttime);
			}

			$endtime = trim($this->input->get('endtime'));
			if($endtime)
			{
				$times = $endtime." 23:59:59";
				$where.=" AND (a.dispatchTime <= '".$times."')";
				$this->tpl->assign("endtime",$endtime);
			}
		}

		$other = trim($this->input->get('other'));
		if($other)
		{
			$where.=" AND (b.order_sn = '".$other."' or b.shipping_number = '".$other."')";
			$this->tpl->assign("other",$other);
		}
		$warehouseId = trim($this->input->get('warehouseId'));
		if($warehouseId){
			$where.= " AND b.shipping_status = {$warehouseId} ";
			$this->tpl->assign("warehouseId",$warehouseId);
		}else{
			$where .= " AND b.shipping_status in (1,2,3,4) "; //限制仓库 必须要为海外仓
		}
		$where.= " AND (b.order_status = 5 or b.shipping_status = 4) "; //已完成或已发货订单
		$orderby = " ORDER BY a.order_id DESC ";
		$fields = "a.order_id,a.order_sn,a.addTime,a.dispatchTime,b.orderweight,b.shipping_realfee,b.consignee,b.remark ";
		$fields.= ",b.shipping_number,b.shipping_expectfee ";
		$join    = " LEFT JOIN db_order_list b ON a.order_id = b.order_id ";
		$list = $this->fun->getalllist("db_order_oversea a", $where, $nowpage, $if_csv, $this->pageSize, $orderby,$fields,$join);

		//搜索总运费计算
		$sql = "SELECT SUM(b.shipping_realfee) as shipping_realfee FROM db_order_oversea a LEFT JOIN db_order_list b ".
			   "ON a.order_id = b.order_id ".$where;
		$results = $this->db->query($sql)->row_array();
		$this->tpl->assign("totalfee",$results['shipping_realfee']);
		

		$pageList = $this->pagenav->page($list["total"], $nowpage, $this->pageSize);
		$this->tpl->assign("totalpage", ceil($list["total"] / $this->pageSize));
		$this->tpl->assign("total", $list["total"]);
		$this->tpl->assign("pageList", $pageList);
		$this->tpl->assign("orderlist", $list["list"]);
		$this->tpl->display("oversea/overseabill.tpl");
	}
	public function ajaxbutton()
	{
		$op = trim($_REQUEST['op']);
		if($op == 'stoversearule')
		{
			/********************************************
			 * 海外仓规则脚本停用 启用
			 ***********************************************/
			$id  = $this->input->get("id");
			$type  = $this->input->get("type");
			$this->db->update("db_oversea_rules",array("status"=>$type),"id=".$id);
			header("location:/oversea/overseaRulesList");
		}
		if($op == 'deloversearule')
		{
			/********************************************
			 * 海外仓规则脚本删除
			 ***********************************************/
			$id  = $this->input->get("id");
			$this->db->delete("db_oversea_rules","id=".$id);
			header("location:/oversea/overseaRulesList");
		}
		//申请库存时搜索海外仓产品
		if($op == "searchProductSku"){
			$psearch_key = trim($this->input->post("psearch_key"));
			$sql = "SELECT * FROM t_overseaproduct WHERE sku like '%{$psearch_key}%' or name like '%{$psearch_key}%' ";
			$rs  = $this->db->query($sql)->result_array();
			$json = json_encode($rs);
			echo $json;exit;
		}
		//导入excel
		if($op=="importExcel"){
			if($this->input->post()){
				//excel导入  更新相关记录 长 宽 高 体积等数据。

				require dirname(__FILE__)."/../../fuman/ClassesExcel/PHPExcel.php";
				$arr_excel_file = $_FILES['file_excel'];
				if(!empty($arr_excel_file)&&$arr_excel_file['error']==0) {
					$fileName = $arr_excel_file["name"];
					//$fileType = $arr_excel_file["type"];
					//$fileSize = $arr_excel_file["size"];
					$tmpFileName = $arr_excel_file["tmp_name"];
					//扩展名判断
					$fileExtName = explode(".", $fileName);
					$extName = $fileExtName[count($fileExtName)-1];
					if (!($extName == "xls" || $extName == "xlsx")) {
						echo "上传的文件扩展名应该为.xls或.xlsx";
						exit;
					}
					if ($extName == 'xlsx') {
						$objReader = new PHPExcel_Reader_Excel2007();
						$objExcel = $objReader->load($tmpFileName);
					} else if ($extName == 'xls') {
						$objReader = new PHPExcel_Reader_Excel5();
						$objExcel = $objReader->load($tmpFileName);
					}
					$sheet = $objExcel->getSheet(0);
					$rows = $sheet->getHighestRow(); //总行数
					$cols = $sheet->getHighestColumn(); //总列数 英文大写字母
					$arrCellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
						'Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU',
						'AV','AW','AX','AY','AZ');
					$cols_length = array_search($cols, $arrCellName); //获取数组下标最大数
					$arr_oversea = array();
					//行
					for($row=2;$row<=$rows;$row++){
						//列
						for($column=0;$column<= $cols_length;$column++){
							$cellValue = $arrCellName[$column].$row; //A2
							$col_val = $sheet->getCell($cellValue)->getValue();
							//运单号
							if($column==0){
								$arr_oversea[$row]['id'] = trim($col_val);
							}
							if($column==1){
								$arr_oversea[$row]['sku'] = trim($col_val);
							}
							if($column==2){
								$arr_oversea[$row]['name'] = trim($col_val);
							}
							if($column==3){
								$arr_oversea[$row]['lengthnum'] = trim($col_val);
							}
							if($column==4){
								$arr_oversea[$row]['widthnum'] = trim($col_val);
							}
							if($column==5){
								$arr_oversea[$row]['heightnum'] = trim($col_val);
							}

						}
					}
					//获取数组信息
					foreach($arr_oversea as $k=>$v){
						$vol = ($v['lengthnum']*$v['widthnum']*$v['heightnum'])/1000000;
						$arr_square = array();
						$arr_square['lengthnum'] = $v['lengthnum'];
						$arr_square['widthnum'] = $v['widthnum'];
						$arr_square['heightnum'] = $v['heightnum'];
						$arr_square['volumenum'] = $vol;
						$this->db->update('t_overseaproduct',$arr_square,"id = '".$v['id']."'");
					}
					echo "更新成功!";exit;

				}

			}else{
				$this -> tpl ->display("oversea/importexcel.tpl");
			}
		}
		//导出excel
		if($op=='outExcel'){
			require dirname(__FILE__)."/../../fuman/ClassesExcel/PHPExcel.php";
			$objExcel = new PHPExcel();

			//设置标题
			$objExcel->setActiveSheetIndex(0)->setCellValue('A1','序号');
			$objExcel->setActiveSheetIndex(0)->setCellValue('B1','商品编号');
			$objExcel->setActiveSheetIndex(0)->setCellValue('C1','商品名称');
			$objExcel->setActiveSheetIndex(0)->setCellValue('D1','长(CM)');
			$objExcel->setActiveSheetIndex(0)->setCellValue('E1','宽(CM)');
			$objExcel->setActiveSheetIndex(0)->setCellValue('F1','高(CM)');

			$sql = "SELECT * FROM t_overseaproduct ORDER BY id DESC ";
			$rs  = $this->db->query($sql)->result_array();
			foreach($rs as $k=>$v){
				$count = $k+2;
				$objExcel->setActiveSheetIndex(0)->setCellValue('A'.$count,$v['id']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('B'.$count,$v['sku']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('C'.$count,$v['name']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('D'.$count,$v['lengthnum']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('E'.$count,$v['widthnum']);
				$objExcel->setActiveSheetIndex(0)->setCellValue('F'.$count,$v['heightnum']);
			}
			$excel_name = date("YmdHis");
			header("Content-type:application/vnd.ms-excel;charset=gb2312");
			header('Content-Disposition: attachment;filename="'.$excel_name.'.xls"');
			header('Cache-Control: max-age=0');
			$objWriter = PHPExcel_IOFactory::createWriter($objExcel, 'Excel5');
			$objWriter->save('php://output');
			exit;

		}
		if($op =='addstock')
		{
			$sku = $this->input->post('sku');
			if($sku =='')
			{
				die('请输入SKU！');
			}
			$sku = explode("\r\n",$sku);
			$skulist = array_unique(array_filter($sku));
			foreach($skulist as $key=>$rs)
			{
				$res = $this->fun->getdatabasesdetail('t_overseaproduct'," AND sku='".$rs."'");
				if($res)
				{
					if($res["status"] ==1)$res["status"] ="正常";
					if($res["status"] ==2)$res["status"] ="清仓";
					if($res["status"] ==3)$res["status"] ="停产";
					if($res["status"] ==4)$res["status"] ="自建";
					$newskulist[]= $res;
				}
			}
			$this->tpl->assign("newskulist",$newskulist);
			$this -> tpl -> display("oversea/addstock.tpl");
		}
		if($op =='getfile')
		{
			$tpid = $this->input->get_post('tpid');
			$res = $this->db->get_where("t_oversea_file","tpid='".$tpid."'")->result_array();
		
		    echo json_encode($res);
			die;
		}
		if($op =='delattfile')
		{
			$id = $this->input->get_post('id');
			$rsdb = $this->fun->getdatabasesdetail('t_oversea_file'," AND id='".$id."'");
			if($rsdb["createUser"] != $_COOKIE["username"])
			{
				echo 201;
				die;
			}
			 $this->db->delete('t_oversea_file', 'id=' . $id);
		    echo 200;
		}
		//确认完成弹出页面
		if($op=="showSureEnd"){
			$id = trim($this->input->get_post("id"));
			$oversea_startId = trim($this->input->get_post('oversea_startId'));
			$oversea_destinationId = trim($this->input->get_post('oversea_destinationId'));
			$sql = "SELECT tasknumber,sku,sum(nowbuynum) as nowbuynum  FROM t_transportlist WHERE taskid = '{$id}' GROUP BY sku ";
			$rs  = $this->db->query($sql)->result_array();
			$this->tpl->assign("oversea_startId",$oversea_startId);
			$this->tpl->assign("oversea_destinationId",$oversea_destinationId);
			$this->tpl->assign('taskId',$id);
			$this->tpl->assign("skulist",$rs);
			$this->tpl->display("/oversea/transportskulist.tpl");
		}

		
		if($op =='savefile')
		{
			$msg = $this->m->savefile();
            if ($msg["st"] != 200) {
                $this->fun->phpalert(2, $msg["txt"]);
            } else {
                $this->fun->phpalert(4, "", '', "/oversea/deliveryplanlist");
            }
		}

		if($op =='savestock')
		{
			$nums = $this->input->post('nums');
			$id = $this->input->post('id');
			$sku = $this->input->post('sku');

		
			if(count($nums)>0)
			{
				foreach($nums as $key=>$rs)
				{
					if($rs){
					$rsdbGOODS = $this->fun->getdatabasesdetail('t_overseastock_goods',' AND id='.$id[$key]);
					
					$postdata = "";
					$postdata["check_in"] = $rs;
					$postdata["check_user"] = $_COOKIE["userid"];

					$this->db->trans_begin();
					$this->db->update('t_overseastock_goods', $postdata, 'id=' . $id[$key]);	//更新入库单
					if($key==0){
						
						$this->db->update('t_overseastock_grn', array('is_check'=>1), 'orderno="'.$rsdbGOODS['orderno'].'"' );
					}
					//保存库存
				

					$where = " sku ='".addslashes($rsdbGOODS["sku"])."'";
					$rsdb = $this->db->get_where('t_overseastock',$where)->result_array();
					if(count($rsdb)==0)	//没有商品
					{
						$postdata="";
						$postdata['sku']		=addslashes($rsdbGOODS["sku"]);
						$postdata['stock']		=$rs;
						$this->db->query($this->db->insert_string('t_overseastock', $postdata));
						$parentID = $this->db->insert_id();
					}else{
						$this->db->query("UPDATE t_overseastock SET stock = stock+$rs where sku='".$rsdbGOODS["sku"]."'");
					}

					
					if ($this->db->trans_status() === FALSE)
					{
						$this->db->trans_rollback();
					}
					else
					{
						$this->db->trans_commit();
					}


					

					}
				}
			}
			header("location:/oversea/stocklist");
		}

		if($op =='savestockout')
		{
			$nums = $this->input->post('nums');
			$id = $this->input->post('id');
			$sku = $this->input->post('sku');
			if(count($nums)>0)
			{
				$this->db->trans_begin();
				$parentID = $this->m->savestockgrn(2);
				$goods_id = $this->m->savestockgoods($sku,$nums,$parentID);
				
				foreach($nums as $key=>$rs)
				{
					$where = " sku ='".$sku[$key]."'";
					$this->db->query("UPDATE t_overseastock SET stock = stock-$rs where sku='".trim($sku[$key])."'");
					
				}


				if ($this->db->trans_status() === FALSE)
				{
					$this->db->trans_rollback();
				}
				else
				{
					$this->db->trans_commit();
				}
			}

			header("location:/oversea/addstocklist?t=2");
		}
		

		if($op =='savepurchasingNext')
		{
			$listdb = $this->m->savepurchasingNext();
		
			echo json_encode($listdb);
			die;
		}
		if($op =='delpurlist')
		{
			$rs = $this->m->delpurlist();
			echo 200;
			die;
		}
		if($op =='demandList')
		{
			$this->demandList();
			
		}
		if($op == 'getpurchprolist')
		{
			$listdb = $this->m->getpurchprolist();
			echo json_encode($listdb);
			die;
		}
		if($op == 'getplanstatus')
		{
			$listdb = $this->fun->getdatabasesdetail('t_transport_status'," AND id='".trim($this->input->post('id'))."'");
			if($listdb){
			echo json_encode($listdb);
			die;
			}else{
				echo 201;
				die;
			}
		}
		if($op == 'getplanstatustask')
		{
			$listdb = $this->fun->getdatabasesdetail('t_transport_status'," AND task_id='".trim($this->input->post('id'))."'");
			if($listdb){
			echo json_encode($listdb);
			die;
			}else{
				echo 201;
				die;
			}
		}
		if($op == 'boxid')
		{
			$listdb = $this->fun->getdatabasesdetail('t_transportbox'," AND boxnumber='".trim($this->input->post('boxid'))."'");
			if($listdb)
			{
				echo 201;
				die;
			}
		}
		if($op == 'getpaixu')
		{
			$id = $this->m->getpaixu();
			header("location:/oversea/warehouse");
		}
		if($op == 'changstatus')
		{
			$id = $this->m->changstatus();
			if(trim($this->input->post("oversea_startId")) || trim($this->input->post("oversea_destinationId"))){
				header("Location:/oversea/transportlist");
			}
			echo $id;
			die;
		}
		
		/*******************
		*** 仓库核实可发货数
		********************/
		if($op =='savedeliveryplanpro')
		{
		
			$submittype = intval($this->input->post('submittype'));
			if($submittype == 1)
			{
				//仓库核实

				$verifyNums = $this->input->post('verifyNums');
				$ID = $this->input->post('ID');
				
				
				if($ID){
					$post= "";
					foreach($ID as $key=>$rs)
					{
						$post[$key]["verify_tip"] = 1;
						$post[$key]["verifyNums"] = $verifyNums[$rs][0];
						$post[$key]["id"] = $rs;
					}
				}
				
				$this->db->update_batch('t_overseapurchasing', $post, 'id');//批量更新
			}
			header("location:/oversea/deliveryplanpro");
		}
		if($op == 'getTchangstatus')
		{
			//请求审核
				
			$t = $this->input->post("t");	// T = 1 请求1审
			$id = $this->input->post("id");

			//如果是外部用户，直接二审完成
			if($_COOKIE['ext_userid'])
			{
				$ext_userID = $_COOKIE['ext_userid'];
				$rsdb = $this->db->get_one("SELECT * FROM t_oversea_demand WHERE id ={$id}  AND (create_id in ($ext_userID)) ");
				if($rsdb)
				{
					$this->db->update("t_oversea_demand",array("status"=>3)," id = '".$id."'");
					return;
				}
			}
			
			

			if($t == 1){
				//设置系统Message提醒
				if($this->config->item('packingman') && $this->config->item('overseatipopen')==1)
				{
						$randid = $this->message->getMessageNums();	//获取当前存储的条数	
						$packingman = explode("|",$this->config->item('packingman'));
						foreach($packingman as $rs)
						{
							$postMessageData["message_type"] = $this->message->getMessageType(2);	//申请库存
							$postMessageData["message"] =$_COOKIE["username"]."[".date("Y-m-d H:i:s")."]"."库存调拨申请 {$orderID}，等待一审";
							$postMessageData["message_toName"] = $rs;
							$postMessageData["isread"] =  $randid;
							$postMessageData["url"] = '/oversea/purchasinglist';
							$this->fun->saveMessage($postMessageData);
						}
				}
				$this->db->update("t_oversea_demand",array("status"=>1)," id = '".$id."'");
			}
		}
		
		if($op == 'deldelitt')
		{
			$id = $this->m->deldelitt();
			echo $id;
			die;
		}
		if($op == 'delproduct')
		{
			$id = $this->m->delproduct();
			echo $id;
			die;
		}
		if($op == 'delstatuslist')
		{
			$id = $this->m->delstatuslist();
			echo $id;
			die;
		}
		if($op == 'deltask')
		{
			$id = $this->m->deltask();
			echo $id;
			die;
		}
		
		if($op == 'delwarehouse')
		{
			$id = $this->m->delwarehouse();
			echo $id;
			die;
		}
		if($op == 'stockout')
		{
			$id = $this->input->post('str');
			if($id)
			{
				$id = substr($id,0,-1);
				$id = explode(",",$id);
				$this->db->where_in('id', $id);
				$list =$this->db->select('*')->from('t_overseastock')->where_in('id',$id)->get()->result_array();
				foreach($list as $key=>$rs)
				{
					$rsdb = $this->fun->getdatabasesdetail('t_overseaproduct' ,' AND sku="'.$rs["sku"].'"');
					$list[$key]["goodsname"] = $rsdb["name"];
				}
				echo json_encode($list);
				die;
			}
		}
		if($op == 'yz')
		{
			$id = $this->m->yz();
			header("location:/oversea/warehouse");
		}if($op == 'st')
		{
			$id = $this->m->st();
			header("location:/oversea/product");
		}
		if($op == 'hw')
		{
			$id = $this->m->hw();
			header("location:/oversea/product");
		}
		if($op == 'getsku')
		{
			$rs = $this->m->getsku();
			if(!$rs)
			{
				echo 200;
			}else{
				echo json_encode($rs);
				die;
			}
		}

		if($op=='showmenu')
		{
			$menu = $this->fun->getmenu();

			echo $menu;
			die;
		}
		if($op =='mergedemand')
		{
			$dw = $this->input->post('dw');
			$demandid_list =trim( $this->input->post('demandid_list'),",");
			$detail = $this->fun->getdatabasesdetail('t_oversea_demand'," AND demand_number='".trim($dw)."'");
			if(!$detail)
			{
				$this->fun->phpalert(2, "不存在的调拨单！", '');
					die;
			}
			if($_COOKIE["department"] ==3)	//销售只允许修改自己的SKU
			{
				if($detail["create_id"] != $_COOKIE["userid"])
				{
					$this->fun->phpalert(2, "不允许修改不属于自己创建的调拨单", '');
					die;
				}
			}
			$list = $this->fun->getdatabaseslist('t_overseapurchasing'," AND id in($demandid_list) AND demandID !={$detail[id]}");
			//echo $this->db->last_query();
			//die;
			if($list)
			{
				foreach($list as $key=>$rs)
				{
					if($rs['sendnums'] == 0)	//说明没有发过
					{
						$sing =  $this->fun->getdatabasesdetail('t_overseapurchasing'," AND demandID='".$detail["id"]."' AND oversearproduct_id='".$rs["oversearproduct_id"]."'");
						
						if($sing)
						{
							//合并
							$skunum = $rs["skunum"]+$sing["skunum"];
							$verifyNums = $rs["verifyNums"]+$sing["verifyNums"];
							$this->db->update("t_overseapurchasing",array("skunum"=>$skunum,"verifyNums"=>$verifyNums),"id=".$sing['id']);
							$this->db->delete("t_overseapurchasing","id=".$rs['id']);
						}else{
							 $this->db->update("t_overseapurchasing",array("demandID"=>$detail['id']),"id=".$rs['id']);
						}
						
					}else{
						//说明之前发过货
					
						
						$skunum = $rs["skunum"] - $rs["sendnums"];//还需要发货数
						//新建一条
						$sing =  $this->fun->getdatabasesdetail('t_overseapurchasing'," AND demandID='".$detail["id"]."' AND oversearproduct_id='".$rs["oversearproduct_id"]."'");
						if($sing)
						{
							$newskunum = $sing["skunum"] + $skunum;
							$this->db->update("t_overseapurchasing",array("status"=>0,"skunum"=>$newskunum,"demandID"=>$detail["id"]),"id=".$sing['id']);//合并存入相同的SKU
							$this->db->delete("t_overseapurchasing","id=".$rs['id']);//原来的那条商品直接删除了
						}else{
							 $this->db->update("t_overseapurchasing",array("demandID"=>$detail['id'],"skunum"=>$skunum,"sendnums"=>0),"id=".$rs['id']);
							/*
							$post="";
							$post["demandID"] = $detail['id'];
							$post["sendnums"] = 0;
							$post["seawarehouse"] = $rs["seawarehouse"];
							$post["seaware_id"] = $rs["seaware_id"];
							$post["shopname"] = $rs["shopname"];
							$post["oversearproduct_id"] = $rs["oversearproduct_id"];
							$post["skunum"] = $skunum;
							$post["goodsno"] = $rs['goodsno'];
							$post["fnsku"] = $rs['fnsku'];
							$post["remark"] = $rs['remark'];
							$post["createUser"] = $rs['createUser'];
							$post["createUID"] = $rs['createUID'];
							$post["opertime"] = $rs['opertime'];
							$this->db->insert('t_overseapurchasing',$post);*/
						}
						
						

					
					}



				}
			}
			$this->fun->phpalert(4, "", '', "/oversea/demandList?id={$detail[id]}");
		}
		if($op=='onegoods')
		{
			$detail = $this->fun->getdatabasesdetail('t_transportationplanning'," AND id='".trim($this->input->post('planid'))."'");
			if($detail)
			{
				$newgoodslist = unserialize($detail["detaillist"]);
				foreach($newgoodslist as $key=>$rs)
				{
					if($rs["sku"] == trim($this->input->post('skuname')) ||  strtolower($rs['sku']) == trim(strtolower($this->input->post('skuname'))))
					{
						$skuname = $this->fun->getdatabasesdetail('t_overseaproduct'," AND sku='".$rs["sku"]."'");
						$rs["sku"] = $skuname["sku"];
						$newgoods[] = $rs;
					}
				}
			}
			
			if($newgoods)
			{
				echo json_encode($newgoods);
			}else{
				echo 201;
				die;
			}
		}
		if($op =='savefnsku')
		{
			$id = intval($this->input->post('id'));
			$fnsku = trim($this->input->post('fnsku'));
			if($fnsku && $id)
			{
				$this->db->update("t_overseapurchasing",array("fnsku"=>$fnsku),"id='".$id."'");
			}
		}
		if($op == 'savefuyi')
		{
			$id = $this->m->savefuyi();
			echo $id;
			die;
		}
		if($op =='savepackingPro')
		{
			$uid =$this->input->post('uid');
			$uid = trim($uid,",");
			$res = $this->fun->getdatabaseslist("t_overseapurchasing"," AND id in($uid)"," DISTINCT shopname ");
			$shop = count($res);
			$demandID = $this->fun->getdatabaseslist("t_overseapurchasing"," AND id in($uid)"," DISTINCT demandID ");

			$keshi = $this->fun->getdatabaseslist("t_overseapurchasing"," AND id in($uid) AND verify_tip =0","id");

			$nocang = $this->fun->getdatabaseslist("t_overseapurchasing"," AND id in($uid) AND verifyNums =0 AND verify_tip= 1","id");

			echo json_encode(array("shop"=>$shop,"demandID"=>count($demandID),"keshi"=>count($keshi),"nocang"=>count($nocang)));
			die;
		}
		if($op =='getshipNums')
		{
			$id =$this->input->post('id');
			$tNums =$this->input->post('t');
			$res = $this->fun->getdatabasesdetail("t_overseapurchasing"," AND id ='".$id."'"," verify_tip,verifyNums");
			if($res["verifyNums"]>=$tNums)
			{
				$msg = array("code"=>200,"verifyNums"=>$res["verifyNums"]);
			}else{
				$msg = array("code"=>201,"verifyNums"=>$res["verifyNums"]);
			}
			echo json_encode($msg);
			die;
		}
		if($op =='changstockform')
		{
			$sku = $this->input->post('sku');
			if($sku =='')
			{
				die('请输入SKU！');
			}

			$sku = explode("\r\n",$sku);
			$skulist = array_unique(array_filter($sku));
			foreach($skulist as $key=>$rs)
			{
		
				$strsku = explode(",",$rs);

				$postdata = "";
				$postdata["stock"] = trim($strsku[1]);

				$this->db->update('t_overseastock', $postdata, 'sku="'.$strsku[0].'"');
			}
			header("location:/oversea/stocklist");
			
		}

		if($op =='showaddstocklist')
		{
			$res = $this->db->get_where('t_overseastock_goods'," orderno='".$this->input->post('orderno')."'")->result_array();
			if(count($res)>0)
			{
				foreach($res as $key=>$rs)
				{
					$rsdb = $this->fun->getdatabasesdetail('t_overseaproduct' ,' AND sku="'.$rs["sku"].'"');
					$res[$key]["goodsname"] = $rsdb["name"];
				}
			}
			echo json_encode($res);
			die;
		}
		/********************************************
		* 查看商品是否存在
		***********************************************/
		if($op =='getgoodssku')
		{
			$newgoods_sn = trim($this->input->get_post('val'));//获取新商品SKU
			$rsdb = $this->fun->getdatabasesdetail("t_overseaproduct"," AND sku = '".$newgoods_sn."'");
			if(!$rsdb)
			{
				$data["code"] = 201;
				$data["txt"] = "商品编号【{$newgoods_sn}】信息不存在,请先添加商品信息！";
				echo json_encode($data);
				die;
			}else{
				$data["code"] = 200;
				$data["txt"] = $rsdb;
				echo json_encode($data);
				die;
			}
		}
		/********************************************
			* 追加新的SKU
		***********************************************/
		if($op =='addorderNewgoods')
		{
			$addgoodsorderID = intval($this->input->post('addgoodsorderID'));
			$ordergoodsno  = $this->input->post('ordergoodsno');	//商品SKU
			$ordergoodsnoNum  = $this->input->post('ordergoodsnoNum');	//商品数量
			$res = $this->fun->getdatabasesdetail("t_oversea_demand"," AND id = '".$addgoodsorderID."'");
			
			if(strstr( $res["seawarehouse"],'Amazon'))
			{
				$amz =1;	//发亚马迅
			}else{
				$amz = 0;	
			
			}

			if(count($ordergoodsno)>0)
			{
				foreach($ordergoodsno as $key=>$rs)
				{
					$nums = intval($ordergoodsnoNum[$key]);
					if(!$nums) $nums =1;
					if(trim($rs)){
						$rsdb = $this->fun->getdatabasesdetail("t_overseapurchasing"," AND demandID = '".$addgoodsorderID."' AND goodsno ='".trim($rs)."'");
						if($rsdb){
							$this->db->query("UPDATE t_overseapurchasing SET skunum = skunum+$nums where id = '".$rsdb["id"]."'");
						}else{
							//更新
							$oversearproduct = $this->fun->getdatabasesdetail("t_overseaproduct"," AND sku = '".trim($rs)."'");
							if($oversearproduct["hw"]==0 && $amz==0)
							{
								$this->fun->phpalert(2, "[{$oversearproduct[sku]}]不在允许发往海外仓列表", '');
								die;
							}else{
								$post="";
								$post["demandID"] = $addgoodsorderID;
								$post["seawarehouse"] = $res["seawarehouse"];
								$post["seaware_id"] = $res["seaware_id"];
								$post["shopname"] = $res["shopname"];
								$post["oversearproduct_id"] = $oversearproduct["id"];
								$post["skunum"] = $nums;
								$post["goodsno"] = trim($rs);
								$post["remark"] = '';
								$post["createUser"] =  $_COOKIE["username"];
								$post["createUID"] = $_COOKIE["userid"];
								$post["opertime"] = date("Y-m-d H:i:s");
								$this->db->insert("t_overseapurchasing",$post);
							}

						}

						//重新计算库存数
						$this->m->getoverseapurchasingdata($addgoodsorderID);
					

					}
				}
			}
			$this->fun->phpalert(4, "", '', "/oversea/demandList?id={$addgoodsorderID}");
		}
		/************
		** 关闭调拨申请
		****************/
		if($op =='closepurchasing')
		{
			$id = $this->input->post("id");
			$this->db->update("t_oversea_demand",array("status"=>4),"id='".$id."'");
			$this->db->update("t_overseapurchasing",array("status"=>2),"demandID='".$id."'");
			echo 200;
			die;
		}
		if($op == 'orderproblem')
		{
			$uid = $this->input->post('uid');
			$uid = substr($uid,0,-1);
			$transportbox = $this->fun->getdatabaseslist('t_transportbox A left join t_transportationplanning B on A.planid=B.id'," AND A.id in($uid)",'B.destination,B.startingplace,A.isQuality,A.id',' order by A.id desc');
			foreach($transportbox as $key=>$rs)
			{
				$startingplace[] = $rs["startingplace"];
				$destination[] = $rs["destination"];

				if($rs["isQuality"]==0)
				{
					$isQuality[] = $rs["id"];
				}
			}
		
			$startingplacenums = count(array_unique($startingplace));
			if($startingplacenums>1)
			{
				echo 201;
				die;
			}
			$destinationnums = count(array_unique($destination));
			if($destinationnums>1)
			{
				echo 202;
				die;
			}
			if($isQuality){
			$isQuality = count(array_unique($isQuality));
			if($isQuality>=1)
			{
				echo 203;
				die;
			}
			}
			echo 200;
			die;
		
			
		}

		if($op =='changisQuality')
		{
			$uid = $this->input->post('uid');
			$uid = substr($uid,0,-1);
			$postdata="";
			$postdata["isQuality"]  = 1;
			$postdata["QualityTime"]  = date("Y-m-d H:i:S");
			$postdata["QualityUser"]  = $_COOKIE["username"];
			$this->db->update("t_transportbox",$postdata," id in ($uid)");
			echo 200;
			die;

		}
	

		

		

	}
	
	
	
}
